Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ngrx/store - The store does not return the data in async/away manner

Tags:

angular

ngrx

I have a problem while getting the value from the store. The operation hangs. I try to get the data in the following way:

async onInit(params: Params) { 
  // it hangs on the line bellow
  var userToken = await this.store.select(fromRoot.getUserToken).toPromise();  
  console.log(userToken);
}

then I execute the following async function:

ngOnInit(): void {
this.route.params.subscribe(params => {
  this.onInit(params).then(() => console.log('promise executed'));
});

The user token is never returned.

If I subscribe to the store then it works fine.

this.store.select(fromRoot.getUserToken).subscribe(ut => {
  console.log(ut);
});
like image 432
aph5 Avatar asked Apr 02 '17 10:04

aph5


1 Answers

I recently had this problem as well. As @maxime1992 indicates you need an operator to end the observable.

    async onInit(params: Params) { 
        // it hangs on the line bellow
        const userToken = await this.store.select(fromRoot.getUserToken).pipe(take(1)).toPromise();  
        console.log(userToken);                                      // ^^^^^^^^^^^^^^     
    }

Update for rxjs 7+, now we use firstValueFrom or lastValueFrom:

    async onInit(params: Params) { 
        // it hangs on the line bellow
        const userToken = await firstValueFrom(this.store.select(fromRoot.getUserToken).pipe(take(1)));  
        console.log(userToken); // ^^^^^^^^^^^^                                                      ^
    }
like image 197
Jeffrey Drake Avatar answered Oct 13 '22 16:10

Jeffrey Drake