我正在尝试让NgRX效果返回一个动作对象。动作对象表示“成功”,并且需要返回所有检索到的机构作为有效负载的一部分。我该怎么做呢?请注意,mergeMap
内部的块不起作用。检索它们后,我需要将所有检索到的机构作为有效载荷的一部分返回。
@Effect()
getInstitutions$ = this.actions$
.ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
.pipe(
switchMap(() => {
const institutions = this.getInstitutions();
console.log(institutions);
return this.getInstitutions();
}),
mergeMap((institutions: Institution[]) => {
// return institutions;
return {
type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
payload: institutions
};
})
);
答案 0 :(得分:1)
您必须像下面这样对this.getInstitutions()
进行操作:
@Effect()
getInstitutions$ = this.actions$
.ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
.pipe(
switchMap(() => {
return this.getInstitutions().pipe(
map(institutions => ({
type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
payload: institutions
})),
catchError(_ => ...) //don't forget to handle errors
)
})
);
作为旁注,我鼓励您使用动作创建者,而不是“在整个地方”创建动作对象-Let’s have a chat about Actions and Action Creators within NgRx
答案 1 :(得分:0)
如何使用“地图”内置的mergeMap。您可以尝试关注吗?
@Effect()
getInstitutions$ = this.actions$
.ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
.pipe(
switchMap(() => {
const institutions = this.getInstitutions();
console.log(institutions);
return this.getInstitutions();
}),
map((institutions: Institution[]) => {
// return institutions;
return {
type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
payload: institutions
};
})
);
希望有帮助!