Why action doesn't trigger Effect the second time it runs?

余生颓废 提交于 2019-12-01 19:35:51

You need to catchError on request instead of the actions$. To do this, you will need to modify your code as following:

mergeMap(action => 
  this.myService.getDocs().pipe(
    map(data => new LoadDocsSuccess(data)),
    catchError(error => Observable.of(new LoadDocsFailure(error)))
  )
)

I guarantee you that this is the right way to do it. How do I know? There is a long talk about this exact issue on the ngrx Udemy course and this is the solution they provide. Note that is is essential to use catchError else an HTTP error response (any non 2xx response) will disable this effect.

@Effect()
  loadDocsEffect$ = this.actions$.pipe(
    ofType(myActionTypes.LoadDocs),
    mergeMap((action) => {
      // essential to catchError else an HTTP error response will disable this effect
      return this.myService.getDocs().pipe(
        map(data => new LoadDocsSuccess(data)),
        catchError((err) => {
          return of(null)
        })
      )
    }),
    tap(res => console.log(res)) // you won't want this line but useful for debugging
  );

In this example, if the HTTP request succeeds the result of new LoadDocsSuccess(data) will be logged inside tap. If the HTTP request fails, null will be logged inside tap. Of course, you may want to provide some different catchError logic but you get the idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!