Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Implement session storage in an Angular 8 application

Writer Sebastian Wright

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> <h2> Welcome to {{title}} </h2>
</section>
<div *ngIf="movies"> <div *ngFor = "let movie of movies['results']"> <img src=' alt="Movie image"> <div> <h5>Title: {{movie.title}}</h5> <p>Year: {{movie.release_date.slice(0, 4)}}</p> <a href="#/" id={{movie.id}}>More details</a> <a href="#/" #{{likeCounter}} id=#{{movie.id}} counting>Likes</a> </div> </div>
</div> 

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

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

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; }
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy