簡體   English   中英

如何從動作 ngxs 接收 http 響應

[英]How to receive http response from action ngxs

如何在發送操作的組件中收到 http 響應。 我不想將結果存儲在組件中。 我只想在組件中使用 http 響應。

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

我嘗試使用像ofActionSuccess這樣的生命周期鈎子,但它只返回我發送的動作。

我查看了文檔,但找不到有關該主題的任何特定信息。

最簡單的方法是select state 你的動作完成后。

例如,在您的組件中是這樣的:

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

正如您所提到的,如果您想在操作后執行某些操作但您沒有分派操作,您也可以使用操作生命周期掛鈎 - 在這種情況下,您也可以再次使用withLatestFrom獲取當前的 state。

這種用法在調度動作的文檔中有所提及。

您可以添加新操作 - GetNovelsComplete

@Action(GetNovels)
getNovels(ctx: StateContext<Novel[]>) {
  return this.novelsService.getNovels().pipe(
    tap(novels => {
      ctx.setState(novels);
      ctx.dispatch(new GetNovelsComplete(novels));
    }),
    catchError(error => {
      ctx.dispatch(new GetNovelsComplete([]));
      return throwError(() => error)
    }),
  );
}

@Action(GetNovelsComplete)
getNovelsComplete() {
}

然后:

this.actions$.pipe(
  ofActionDispatched(GetNovelsComplete)
).subscribe(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM