How to receive http response from action ngxs

Viewed 557

How can I receive http response in component where I dispatch the action. I don't want to store result in the component. I only want to use http response in the component.

@Action(GetNovels, { cancelUncompleted: true })
  getNovels(ctx: StateContext<Novel[]>) {
    return this.novelsService.getNovels().pipe(
      tap(novels => {
        ctx.setState(novels);
      })
    );
  }

I tried to use life cycle hooks like ofActionSuccess but it is only returns the action I dispatched..

I look at the document but couldn't find any particular information about the subject.

1 Answers

The simplest way is to select the state after your action is completed.

E.g. in your component something like this:

this.store.dispatch(new GetNovels())
.pipe(
  withLatestFrom(this.store.select(NovelsState)),
  tap(([_, novelsState]) => {
     // do something with the 'response' which is now captured in the new state
  }),
).subscribe();

As you mentioned you could also use the action lifecycle hooks if you want to do something post-action but you didn't dispatch the action - again you could also grab the current state using withLatestFrom in that case.

This usage is touched on in the documentation for dispatching actions.

Related