Angular Observable data lost on refresh ,is there way to save data even after refresh

Published

I am using BehaviourSubject from Shared Service whenever I refresh the page I am getting null as a response, it loses the last emit event data

Source: Angular Questions

Published
Categorized as angular, observable, refresh Tagged , ,

Answers

If you want to retain a value of a BehaviourSubject even after refresh one approach could be to use localStorage and retrieving value when component loads:

export class AppComponent implements OnInit {
  private localKey="myVal";
  myVal = new BehaviorSubject(localStorage.getItem(this.localKey)??null);
  ngOnInit(){
    this.myVal.subscribe(newVal=>{
      localStorage.setItem(this.localKey,newVal);
    })
  }
}

stackBlitz

Because localStorage stores value only in form of string, you can only store literals (except symbols) or plain Object/arrays having literals (you need to stringify and parse in JSON format for them).


Helene Parisian MD

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq