Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement session storage in an Angular 8 application

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> 
like image 557
Darotudeen Avatar asked Oct 22 '19 09:10

Darotudeen


People also ask

Can we use session in Angular?

It can only be used in a modern browser. When the window is closed or reopened while in session storage, the data is retained; however, when the tab is closed, the data will be lost. It's easy to create a new Angular project create a new Angular project using a command.


3 Answers

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

like image 70
Ling Vu Avatar answered Oct 04 '22 00:10

Ling Vu


You can use either Session storage or Local storage to store the data temporarily.

Session storage will be available for specific tab where as we can use Local storage through out the browser. Both are default to same origin and we can also store values manually with key, value pairs (value must be string).

Once tab (session) of the browser is closed then Session storage will be cleared on that tab, where as in case Local storage we need to clear it explicitly. Maximum storage limit respectively 5MB and 10MB.

We can save and retrieve the data like 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

like image 25
Ganesh Avatar answered Oct 04 '22 00:10

Ganesh


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;

    }
like image 28
eHayik Avatar answered Oct 03 '22 22:10

eHayik