CNIS
CNIS

Reputation: 121

Why is the object I try to retrieve from the localstorage null and after reload it is defined?

I am using NGX-Webstorage: https://www.npmjs.com/package/ngx-webstorage.

I have a login function in my auth.service

login(username, hashedPassword){
    return this.http.get(this.api + 'login', {params: {username: username, password: hashedPassword}})
    .subscribe(user => {
      if(user){
       this.initilizeApp(user);
       this.router.navigate(['/assignments'])
      } else {...}
    }, error => {
      console.log(error);
    })
  }

There are constants in my app which I try to store in the localstorage in the function initilizeApp() which is working

initilizeApp(user){
    forkJoin({data1: getData1(user.ID), data2: getData2()}).subscribe(val => {
       val.user = {};
       val.user = user;
       this.localStorage.store('init', val)
    }) // has user object
}

The problem is, after the intitialization part in the login function, I navigate to assignments and in ngOnInit I try to retrieve the user from the localstorage:

ngOnInit(){
    this.user = this.localStorage.retrieve("init").user;
}

but user is undefined and after reload user is defined. Since storeand retrieve are sync functions, I don't know why the object isnt in the localstorage when I try to retrieve it directly after storage..

Upvotes: 0

Views: 353

Answers (1)

Gérôme Grignon
Gérôme Grignon

Reputation: 4228

After retrieving the user from the http request, you change your observable to return the value of the new forkjoin observable. This way the navigation will only happens when the localStorage value is saved.

login(username, hashedPassword){
    return this.http.get(this.api + 'login', {params: {username: username, password: hashedPassword}})
    .pipe(
      filter(user => !!user)
      switchMap(user => {
        return forkjoin({data1: getData1(user.ID), data2: getData2()})
      })
    )
    .subscribe(user => {
       // you shouldn't need to nest the user into a 'val' object
       this.localStorage.store('init', user)
       this.router.navigate(['/assignments'])
    }, error => {
      console.log(error);
    })
  }

Except if there is a special need to nest the user into a 'val' object, you can retrieve it this way.

ngOnInit(){
    this.user = this.localStorage.retrieve("init");
}

Upvotes: 2

Related Questions