codeBelt
codeBelt

Reputation: 1805

ngrx store selector triggers effect request without action

Using Angular 6 and NGRX.

I use a store selector in the effect to get data for the request. After the first time I call the action SignalAction.LOAD_SIGNAL if at any point after that there is a store change that cause the selector getRequestParams to update. A request is triggered without the action being fired.

Is there a different way I should be handling this? I only want the observable stream to run through fully on an action.

I've tried take(1) after the store selector but then the request only works once.

@Injectable()
export class SignalEffect {

    constructor(
        private _signalService: SignalService,
        private _actions$: Actions,
        private _store$: Store<IStore>,
    ) {}

    @Effect()
    public fetchSignal(): Observable<IAction<SignalModel[] | HttpErrorResponse>> {
        return this._actions$
            .ofType(SignalAction.LOAD_SIGNAL)
            .pipe(
                switchMap((action: IAction<void>) => this._store$.select(getRequestParams)),
                switchMap((requestParams: RequestParamsModel) => {
                    return this._signalService.getSignal(requestParams)
                        .pipe(
                            map((responseModel: SignalResponseModel | HttpErrorResponse) => {
                                if (responseModel instanceof HttpErrorResponse) {
                                    return ErrorsAction.requestFailure(responseModel);
                                }

                                return SignalAction.loadSignalSuccess(responseModel.results);
                            }),
                        );
                }),
            );
    }

}

Upvotes: 2

Views: 2786

Answers (1)

Joshua Chan
Joshua Chan

Reputation: 1847

Try moving your first .pipe to before ofType.

@Effect()
public fetchSignal(): Observable<IAction<SignalModel[] | HttpErrorResponse>> {
  return this._actions$
    .pipe(
      ofType(SignalAction.LOAD_SIGNAL),
      withLatestFrom(this._store$.select(getRequestParams)),
      switchMap(([action, requestParams: RequestParamsModel]) => {
        return this._signalService.getSignal(requestParams)
          .pipe(
            map((responseModel: SignalResponseModel | HttpErrorResponse) => {
              if (responseModel instanceof HttpErrorResponse) {
                return ErrorsAction.requestFailure(responseModel);
              }

              return SignalAction.loadSignalSuccess(responseModel.results);
            }),
        );
      }),
  );

Upvotes: 3

Related Questions