angulartypescriptangular-ssr

Localstorage is not defined Angular


I'm building this project and got stuck with localStorage. I'm trying to save the count state when add button is clicked. So that when I refresh the page, the number is still there.

--- cart.service.ts---
key= "count";


private Count = new BehaviorSubject<number>(this.getlocal());
Count$ = this.Count.asObservable();

incrementCount(){
   const newCont = this.Count.value+1;
   this.Count.next(newCont);
   this.setlocal(newCont);
 }


 getlocal(): number {
  const storedValue = localStorage.getItem(this.key); 
  return storedValue !== null ? parseInt(storedValue, 10) : 0;
}

setlocal(count: number) {
  localStorage.setItem(this.key, count.toString());
}

Then I have an app component with the incrementcount function. And a navcomponent that receive the count through html. Error ng0100 ..help me fix this pls!


Solution

  • When using SSR, and you want to use browser APIs, you need to wrap this code in afterRender or afterNextRender, otherwise this code may be executed on server side (Node.JS), where localStorage does not exist. Also you cannot directly return the value from local storage in a function, you will need to adjust the logic to load the value from the storage.

    private Count = new BehaviorSubject<number>(0);
    
    constructor(private readonly environmentInjector: EnvironmentInjector) {
      afterNextRender(() => {
        const storedValue = localStorage.getItem(this.key);
        const count = storedValue !== null ? parseInt(storedValue, 10) : 0;
        this.Count.next(count);
      });
    }
    
    setlocal(count: number) {
      runInInjectionContext(this.environmentInjector, () =>
        afterNextRender(() => localStorage.setItem(this.key, count.toString()))
      );
    }