Use of localstorage with Angular Universal SSR (Server Side Rendering) if is undefined or not defined
What are the questions this article covers:
- LocalStorage with Angular Universal
- localStorage is not defined in Angular Universal
- How to use localStorage in angular universal
- localStorage is not defined using angular universal
- Use of LocalStorage with Angular Universal
- localStorage undefined Angular Server Side Rendering
- Angular Universal Server Side Rendering
Angular universal doesn't support the global variables like windows, documents, localstorage etc..
In that case we get undefined error for these variables.
Here I am discussing on the localstorage not defined error in angular universal SSR.
When we implement angular universal SSR , we have to install '@ng-toolkit/universal'
This comes with the alternative the global variables like localstorage , windows..
So the very first step is to import from library
import { LOCAL_STORAGE } from '@ng-toolkit/universal';
Now create the instance for the local_storage at constructor level by forcefully injecting using parameter decorator @Inject().
constructor( @Inject(LOCAL_STORAGE) private localStorage: any ) { }
You can create a separate service file of the localstorage methods.
Create a file localstorage.service.ts and copy paste the below code.
import { Injectable, Inject } from '@angular/core';
import { LOCAL_STORAGE } from '@ng-toolkit/universal';
@Injectable()
export class PersistanceService {
constructor(@Inject(LOCAL_STORAGE) private localStorage: any ) { }
set(key: string, data: any): void {
try {
this.localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error saving to localStorage', e);
}
}
get(key: string) {
try {
return JSON.parse(this.localStorage.getItem(key));
} catch (e) {
console.error('Error getting data from localStorage', e);
return null;
}
}
}
Now you can easily get and set values in the localstorgae with angular universal while using ( SSR ) Server side rendering.