9

我有效果类,我想根据路由器参数 ID 加载详细信息

@Effect()
  getDetails$ = this.actions$.ofType(DetailActions.GET_DETAILS).pipe(
    map(toPayload),
    switchMap(payload => {
      return this.detailService
        .getDetail(payload)//I want router params here in payload
        .pipe(
          map(detail=> new DetailActions.GetDetailSuccess(detail)),
          catchError(error =>
            Observable.of(new DetailActions.GetDetailFail(error))
          )
        );
    })
  );

我想在有效负载中获取路由器参数,这样我就不必从组件传递有效负载,而是直接从效果类中获取它。

4

1 回答 1

13

如果您已经有一个选择器映射到您的应用路由器状态:

export const getRouterState = createFeatureSelector<
  fromRouter.RouterReducerState<RouterStateUrl>
>('router');

然后您可以使用withLatestFrom fromrxjs/operators从路由器状态获取您的参数,并可能将它们与您的操作的有效负载合并,如下所示:

@Effect()
getDetails$ = this.actions$.pipe(
    ofType(DetailActions.GET_DETAILS),
    withLatestFrom(
        this.store.select(fromRoot.getRouterState),
        (action, router) => {
            // do your logic here
            // and return a newPayload:
            return {
                id: router.state.params.id,
                payload: action.payload
            }
        }
    ),
    switchMap(newPayload => {
        return this.detailService
        .getDetail(newPayload)
        .pipe(
            map(detail=> new DetailActions.GetDetailSuccess(detail)),
            catchError(error => Observable.of(new DetailActions.GetDetailFail(error)))
        );
    })
);
于 2018-02-06T20:42:39.067 回答