How to get current value of State object with @ngrx/store?

后端 未结 10 1530
失恋的感觉
失恋的感觉 2020-12-08 06:13

My service class, before calling a web service, needs to get a property called dataForUpdate from my state. Currently, I\'m doing it like this:



        
10条回答
  •  孤街浪徒
    2020-12-08 07:04

    Following the answer from @Sasxa, the syntax changed on newer versions of @nrgx/store (v5 and v6). After the underlying RxJS library was updated to ^5.5.0, there is now a pipe method available on all the Observable instances, which allows for easier chaining and changes how a subscription is achieved.

    So you can now do something like:

    import { take } from 'rxjs/operators';
    
    function getState(store: Store): State {
       let state: State;
    
       store.select('your-state').pipe(take(1)).subscribe(
          s => state = s
       );
    
       return state;
    }
    

    Or, using strictly the pipe() operator:

    import { select } from '@ngrx/store';
    import { take } from 'rxjs/operators';
    
    function getState(store: Store): State {
       let state: State;
    
       store.pipe(select('your-state'), take(1)).subscribe(
          s => state = s
       );
    
       return state;
    }
    

    And if you want to make your code a bit more readable you can also employ async/await mechanics like so:

    import { select } from '@ngrx/store';
    import { take } from 'rxjs/operators';
    
    function async getStateAsync(store: Store): State {
       let state = await store
                 .pipe(
                    select('your-state'),
                    take(1)
                 )
                 .toPromise();
    
       return state;
    }
    

提交回复
热议问题