javascriptangularrxjsredux-observableangular-redux

Fire an action before sending request in redux-observable epic


I want to fire an action before sending a request to the server. Here is my code:

public fetchUserPrjects(action$: Observable<IProjectAction>, store: Store<IAppState>) {
    return action$.pipe(
      ofType(ProjectActionType.FETCH_USER_PROJECTS),
      mergeMap((action) => {
        store.dispatch(this._commonAction.showLoading()); // <== call action before request
         return this._projectService.getProjectList(action.payload)
          .map((result) => {
               return {
              project: result
            };
          });
      }),
      flatMap(data => [
        this._projectAction.addUserProjects(data),
        this._commonAction.hideLoading()
      ])
    ).catch((error) => {
      return Observable.of(this._commonAction.showError(error));
    })
    .concat(Observable.of(this._commonAction.hideLoading()));
  }

I have tried many ways and ended up this way. However, this way sometimes works but sometimes doesn't. Sometimes it freezes whole the process. How can I fire an action before sending the request to the server?


Solution

  • You could remove the showLoading dispatch from your fetchUserProjects epic and then just create a second epic with:

    return action$.pipe(
          ofType(ProjectActionType.FETCH_USER_PROJECTS),
          map(() => this._commonAction.showLoading())
        );
    

    The order of the execution does not really matter because the request this._projectService.getProjectList is asynchronous and will therefore definitely resolve afterwards.