Storage in Angular
Data Storage -------------------|----------- Local
|------------- Cookie
|------------- Session
|------------- Service
Local Storage ----- // Store
localStorage.setItem("email", "email@example.com");Cookie Storage ----- Cookies are small packages of information that can be temporarily stored by your browser
npm install ngx-cookie-service
AppModule
import { CookieService } from 'ngx-cookie-service'
providers :[ CookieService]
In the example code below, we are going to use our AppComponent and use the set and get method of the CookieService. We injecting this service in the parameters of the constructor. Inside the ngOnInit method, we set a new cookie and get that same cookie.
In the first line, we set a new cookie called cookie-name with some random value. On the second line, you can see how to get the cookie value;
AppComponent
import { CookieService } from 'ngx-cookie-service'
private cookieValue :string;
constructor ( private cookieService: CookieService){}
public ngOnInit(): void {
this.cookieService.set ('cookieName' ,'our cookie value')
this.cookieValue = this.cookieService.get('cookieName')
Besides the get and set methods, there are more methods available inside this package like check , getAll , delete and deleteAll , they are showed in the example below.
check(name :string ): boolean;
set(
name:string,
value:string,
expires?:number | date,
path?: string,
domain?:string,
secure?:boolean,
sameSite?: 'Lax' | 'strict'
):void;
get(name:string):string;
getAll():{};
delete (name:string, path?:stirng, domain?:string) :void;
deleteAll(path?:string,domain?:string):void;
Next Upcomming......
Session Storage -----
Service Storage -----
Comments
Post a Comment