Home > Blockchain >  How i can get last value of state? without subscribing (rxJs)
How i can get last value of state? without subscribing (rxJs)

Time:10-28

i have this on facade

chatMessagesState$ = this.store.pipe(select(ChatMessageSelectors.getChatMessagesState));
 

this on selector

export const getChatMessagesState = createSelector(
  getChatMessages,
  (payload: ChatMessagesState) => payload
);

and this on component

   this.chatMessagesSub = this.chatMessagesFacade.chatMessagesState$.subscribe(state => {
        if (state.messages) {
        // do something
        }
  });
    

how i can take state, without subscribing?

CodePudding user response:

 constructor(private storeState: State<YourState>)

 const state = this.storeState.value['your-state'];

If you need to take the value just 1 time

CodePudding user response:

One way is to convert the Observable to a Promise and use async-await:

async getStateValue(){
    const state=await this.chatMessagesFacade.chatMessagesState$.toPromise();
    return state;
  }

Note: This method defeats the purpose of Observables because you won't be able to listen to changes emitted. Promise will either resolve/reject only once.

  • Related