我有以下
<p class="lead" style="text-align:center"><strong>click the below button </strong></p>
问题是,在withLatestFrom中,我想在选择器中使用一个来自动作的参数。我该如何实现?
createMission$ = this.actions$.pipe(
ofType<featureActions.CreateMissionRequest>(featureActions.ActionTypes.CreateMissionRequest),
withLatestFrom(this.store$.select(MissionsStoreSelectors.getById(), {id : action.payload.routeId}))
switchMap((action) =>
this.dataService.createMission(action.payload.mission).pipe(
map(response => new featureActions.CreateMissionSuccess({response, mission : action.payload.mission})),
catchError((error: HttpErrorResponse) => {
this.snackBar.open(this.translate.instant('ERROR.HTTP.GENERIC'), this.translate.instant('BUTTON.OK'), {duration: 2500});
return of(new featureActions.CreateMissionFailed({error}));
}),
),
),
);
编辑:我尝试过
withLatestFrom(this.store$.select(MissionsStoreSelectors.getById(), {id : action.payload.routeId}))
switchMap((action, valueFromLatest) =>
但是我在action.payload(action变成了一个数字)上输入错误,似乎不起作用
答案 0 :(得分:1)
您可以使用switchMap
和combineLatest
来实现这一点,但是我没有在您的代码中看到要使用选择器结果的数据(来自选择器的数据) 。我假设原始动作(CreateMissionRequest
)在其有效负载中具有两个属性:routeId
和mission
。但这没有任何意义,因为您使用了选择器,而不再使用它的结果。但是您可以从下面的技术中获得整体想法,并做您想做的一切。
createMission$ = this.actions$.pipe(
ofType<featureActions.CreateMissionRequest>(featureActions.ActionTypes.CreateMissionRequest),
// This is where you use the switchMap
switchMap((action) =>
// combineLatest here makes it possible to pass forward the results
// from the selector and the original action if you need
combineLatest([
this.store$.pipe(select(MissionsStoreSelectors.getById(), {id : action.payload.routeId}),take(1)),
of(action.payload.routeId),
])),
switchMap(([mission,routeId]) =>
this.dataService.createMission(mission).pipe(
map(response => new featureActions.CreateMissionSuccess({response, mission})),
catchError((error: HttpErrorResponse) => {
this.snackBar.open(this.translate.instant('ERROR.HTTP.GENERIC'), this.translate.instant('BUTTON.OK'), {duration: 2500});
return of(new featureActions.CreateMissionFailed({error}));
}),
),
),
);
实际上,如果您只需要将一个可观察的对象转换为另一个对象,则switchMap
可以为您完成这项工作,而无需combineLatest
:
createMission$ = this.actions$.pipe(
ofType<featureActions.CreateMissionRequest>(featureActions.ActionTypes.CreateMissionRequest),
switchMap((action) =>
this.store$.pipe(select(MissionsStoreSelectors.getById(), {id : action.payload.routeId}),take(1))),
switchMap((mission) =>
this.dataService.createMission(mission).pipe(
map(response => new featureActions.CreateMissionSuccess({response, mission})),
catchError((error: HttpErrorResponse) => {
this.snackBar.open(this.translate.instant('ERROR.HTTP.GENERIC'), this.translate.instant('BUTTON.OK'), {duration: 2500});
return of(new featureActions.CreateMissionFailed({error}));
}),
),
),
);