Questions

LocalStorage Is Not Defined In Angular Universal?

Spread the love

In this tutorial we will describe you how to implement local storage without getting any error:
we will show you two way we can solve the local storage error. 1. from server side. 2. from client side.

ERROR ReferenceError: localStorage is not defined

1. From server side

Local store will render at server side by using localstoreage-poyfill library that hold proxy browser support at server end. This way is faster render of you application.

First install the package by node package manager to implement in-memory localStorage to allow at server side.

npm install localstorage-polyfill

Now open the server.ts file and add the code to it.

import 'localstorage-polyfill';
global['localStorage'] = localStorage;
add localstorage polyfill package in server.ts for use of local storage at server side rendering

build your project again with npm run build:ssr and serve with npm run serve:ssr.

Hope your all the localStorage errors have been stamp out now. Please give your valuable feedback. If you have any kind of questions or issues about this article, please let me know.

2. From client side

Local store will render at client side until navigation end from browser. Follow the code below. This is lengthy process because wherever you use local storage there you have to you use this process or you may reduce your code by only one place mange your application local storage by service that way you can reduce code.

set, get remove of any localStorage item after Navigation end

This is your component page.

  constructor(
    private _localStorageService: LocalStorageService ,
    private router: Router) {
          router.events.subscribe(event => {
             if (event instanceof NavigationEnd) {
                 const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || this.router.url;
                 this._localStorageService.setData('returnUrl', returnUrl);
             }
          })
  }

This the localStorage service page.

import { Router, NavigationEnd, ActivatedRoute, NavigationStart } from "@angular/router";
.............
........... 
@Injectable({
    providedIn: 'root'
})
export class LocalStorageService { 
  setData(setItem,data){
        localStorage.setItem(setItem, data);
  }

 getData(getItem){
        return localStorage.getItem(getItem);
  }

}

Also, check How to solve window is not defined in angular universal?


Spread the love
Tagged , , , , , , , ,

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

4 thoughts on “LocalStorage Is Not Defined In Angular Universal?

Leave a Reply

Your email address will not be published. Required fields are marked *