Implement session storage in an Angular 8 application
Asked Answered
L

3

28

I am building a movie application to aid my learning. I will like to know how to capture and save the number of clicks on button in session storage.

I have been able to get the click working. It increases and display number of click on each button, I did this with a directive. I also tried to attached the id of the button as key and number of click as value to session storage and I could see that it works when I logged it but it seem not to remain whenever I refresh the page.

NB: I am using an API to fetch my data

Landingpage component

import { CountClicks } from './counter.directive';
import { HttpService } from './../http.service';
import { Component, OnInit, ElementRef } from "@angular/core";


@Component({
  selector: "app-landing-page",
  templateUrl: "./landing.component.html",
  styleUrls: ["./landing.component.scss"]
})
export class LandingPageComponent implements OnInit {
  constructor(private _http: HttpService, private elRef:ElementRef) {}
  movies: Object;
  title = "CORNFLIX";
  ids:any;
  storage:any;
  public likeCounter: number = 0;
  ngOnInit() {
    this._http.getMovies().subscribe(data => {
      this.movies = data;
      // for (let x of data['results']){
      //   if(sessionStorage.getItem('#'+x.id) != null){
      //     console.log("#" + x.id);
      //     this.ids = sessionStorage.getItem("#" + x.id);
      //     console.log(this.ids);
      //   }

      // }
      // console.log(this.ids);
    });
    this.storage = sessionStorage
    console.log(this.storage)
  }

Directive for increasing likes

import { Directive, HostListener } from "@angular/core";

@Directive({ selector: "a[counting]" })


export class CountClicks {
  numberOfClicks = 1;
  number:any
  store:any;
  getValue:any;
  
  
  @HostListener("click", ["$event.target"])
  onClick(a): void {
    
    a.innerHTML = `Likes ${this.numberOfClicks++}`;
    this.number = this.numberOfClicks+1
    // console.log(localStorage.getItem(a.id));
    if(sessionStorage.getItem(a.id)){
        this.number = sessionStorage.getItem(a.id);
        // sessionStorage.clear()
    }
    this.store = sessionStorage.setItem(a.id, a.innerHTML);
    this.getValue = sessionStorage.getItem(a.id)
    a.innerHTML = this.getValue;
    // console.log("button", btn.id, "number of clicks:", this.numberOfClicks++);
  }
}

I want to be able to access the DOM and have the session storage update likes on each buttons

<section class="jumbotron">
    <h2>
       Welcome to {{title}}
    </h2>

</section>

<div *ngIf="movies" class="container-fluid d-flex p-2 bd-highlight mb-3 flex-wrap  justify-content-between">
    
    <div *ngFor = "let movie of movies['results']" class="card d-block mb-3 " style="width: 18rem;">
        <img src='https://image.tmdb.org/t/p/w500{{movie.poster_path}}' class="card-img-top" alt="Movie image">
        <div  class="card-body">
            <h5  class="card-title">Title: {{movie.title}}</h5>
            <p class="card-text">Year: {{movie.release_date.slice(0, 4)}}</p>
            <a href="#/" class="btn btn-color" id={{movie.id}}>More details</a>
            <a href="#/"   class="btn btn-color" #{{likeCounter}} id=#{{movie.id}} counting>Likes</a>
        </div>
    </div>
</div> 
Lookthrough answered 22/10, 2019 at 9:14 Comment(0)
P
32

For saving values while refreshing the page, you can use the localStorage or the sessionStorage for that. There is no external library or import necessary. It should work out of the box in most of the browsers.

For saving:

// clicks is the variable containing your value to save
localStorage.setItem('clickCounter', clicks);
// If you want to use the sessionStorage
// sessionStorage.setItem('clickCounter', clicks);

For loading:

const clicks = localStorage.getItem('clickCounter');
// If you want to use the sessionStorage
// const clicks = sessionStorage.getItem('clickCounter');

You can check this in Chrome using the dev tools.

enter image description here

Phylogeny answered 22/10, 2019 at 9:21 Comment(0)
L
25

You can use either session storage or local storage to store the data temporarily.

Session storage will be available for specific tabs, and we can use Local storage throughout the browser. Both are defaulted to the same origin, and we can also store values manually with key-value pairs (the value must be a string).

Once the tab (session) of the browser is closed, session storage will be cleared on that tab, whereas in the case of local storage, we need to clear it explicitly. The maximum storage limits for these storages are 5 MB and 10 MB, respectively.

We can save and retrieve the data as below:

To Save:

sessionStorage.setItem('id', noOfClicks);   // localStorage.setItem('id', noOfClicks);

sessionStorage.setItem('userDetails', JSON.stringify(userDetails));   // if it's object

To Get

sessionStorage.getItem('id');    // localStorage.getItem('id');

User user = JSON.parse(sessionStorage.getItem("userDetails")) as User;  // if it's object

To Modify:

sessionStorage.removeItem('id');    // localStorage.removeItem('id');

sessionStorage.clear();   // localStorage.clear();

P.S: getItem() also return back the data as string and we need convert it into JSON format to access if it's object.

You can read more about Browser Storages here..

  1. Difference between localStorage, sessionStorage and cookies

  2. localstorage-vs-sessionstorage

Lamonicalamont answered 22/10, 2019 at 9:21 Comment(0)
Q
3

You could use ngx-webstorage module

Firstly you must add it as a dependency in your Angular project

npm install --save ngx-webstorage

Then declare the library in your main module e.g.

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {NgxWebstorageModule} from 'ngx-webstorage';

@NgModule({
    declarations: [...],
    imports: [
        BrowserModule,
        NgxWebstorageModule.forRoot(),
        //NgxWebstorageModule.forRoot({ prefix: 'custom', separator: '.', caseSensitive:true }) 
        // The forRoot method allows to configure the prefix, the separator and the caseSensitive option used by the library
        // Default values:
        // prefix: "ngx-webstorage"
        // separator: "|"
        // caseSensitive: false
    ],
    bootstrap: [...]
})
export class AppModule {
}

and finally Inject the services you want in your components and/or use the available decorators e.g.

import {Component} from '@angular/core';
import {LocalStorageService, SessionStorageService} from 'ngx-webstorage';

@Component({
    selector: 'foo',
    template: `foobar`
})

    export class FooComponent {

        constructor(private localSt:LocalStorageService) {}

        ngOnInit() {
            this.localSt.observe('key')
                .subscribe((value) => console.log('new value', value));
        }

    }

    import {Component} from '@angular/core';
    import {LocalStorage, SessionStorage} from 'ngx-webstorage';

    @Component({
        selector: 'foo',
        template: `{{boundValue}}`,
    })
    export class FooComponent {

        @LocalStorage()
        public boundValue;

    }
Quincy answered 22/10, 2019 at 9:26 Comment(1)
How do I get and set in this example?Coetaneous

© 2022 - 2024 — McMap. All rights reserved.