Home > Software design >  Angular: How to save Id in localStorage?
Angular: How to save Id in localStorage?

Time:07-22

For example on my site I have a Url:

http://localhost:4200/help?id=614e163c-62cd-4e05-bf53-20ef340170fe

I want to save the id in localStorage and not display it in the url.

My code for this sample:

ts:

navigate(nav:string){
    this.router.navigate([`/${nav}`], { queryParams: {id: this.user?.id}})
              .then(() => {
          window.location.reload();
    });
  }

html:

<li >
    <a (click)="navigate('help')" >How to play?</a>
</li>

CodePudding user response:

Hope you are doing well.

Not sure about what do you mean by not display it in the url but as for the other part i.e. I want to save the id in localStorage, I hope the follwing code helps:

  constructor(private route : ActivatedRoute, private router: Router){
    this.route.queryParams.subscribe((params : any) => {
      localStorage.setItem('id', params['id']);
    });
  }

You can see the id in the localStoarge(in Application tab). Screenshot attached

Hope this helps. Let me know if any other query.

CodePudding user response:

Basend on the snippets you shared, I guess following should work:-

navigate(nav:string){
    this.router.navigate([`/${nav}`]).then(() => {
      localStorage.setItem('userId', this.user?.id)
    });
  }

CodePudding user response:

Use the skipLocationChange property could be used to protect a user from seeing URL change. Or use replaceUrl to "hide/obfuscate" it from url which user sees. Use localStorage.setItem() to set item in localStorage. Though users also have access to localStorage, so it's not completely hidden. If you really want to hide it, store the id in memory (e.g an Angular service) but just so you know, when you do window.reload() all services and memory is wiped.

https://angular.io/api/router/NavigationBehaviorOptions#skipLocationChange

navigate(nav:string){
    this.router.navigate([`/${nav}`], { queryParams: {id: this.user?.id}, skipLocationChange: true})
              .then(() => {
 localStorage.setItem('id', this.user?.id);
          window.location.reload();
    });
  }
  • Related