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

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);
});


Solution 1:[1]

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); // ^^^^^^^^^^^^                                                      ^
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1