[英]How can I return multiple actions from a nested rxjs operator
我無法在以下效果中分派多個操作:
@Effect()
someEffect$ = this.actions$.pipe(
ofType(someAction: Actions),
mergeMap(
(action)=>{
return this.authService.getProfile(action.payload.authInfo).pipe(
map((response: any) => {
if (response.isErrorResponse) {
return new HeaderActions.AuthFail(response);
} else {
//here i'd like to return multiple actions
return [
new HeaderActions.FetchMPInfoSuccess(this.fetchMpInfoSuccesState(getMpProfileResponse)),
new HeaderActions.GetAccountStates(true)
]
}
}),
catchError((error:HttpErrorResponse )=>{
return of(new HeaderActions.AuthFail(response));
})
);
}
)
);
我嘗試在返回塊中添加一組動作,但這給出了一個錯誤,即我沒有發送有效的動作,知道我做錯了什么嗎?
您可以使用switchMap而不是mergeMap 。 然后使用flatMap或switchMap代替map 。
代碼應該是這樣的:
@Effect()
someEffect$ = this.actions$.pipe(
ofType(someAction: Actions),
switchMap(
(action)=>{
return this.authService.getProfile(action.payload.authInfo).pipe(
flatMap((response: any) => {
if (response.isErrorResponse) {
return new HeaderActions.AuthFail(response);
} else {
//here i'd like to return multiple actions
return [
new HeaderActions.FetchMPInfoSuccess(this.fetchMpInfoSuccesState(getMpProfileResponse)),
new HeaderActions.GetAccountStates(true)
]
}
}),
catchError((error:HttpErrorResponse )=>{
return of(new HeaderActions.AuthFail(response));
})
);
}
)
);
要訪問子組件中的數據,您可以將此方法與 @Input() 設置內容一起使用:
@Input() set(data: any) {
if (data) { console.log(data) }}
html 中的數據將一直存在。
Map修改源 Observable 發出的每個項目並發出修改后的項目。
FlatMap , SwitchMap還對每個發射的項目應用 function 但不是返回修改后的項目,而是返回可以再次發射數據的 Observable 本身。
FlatMap合並多個 Observable 發出的項目並返回單個 Observable。
SwitchMap與 FlatMap 有點不同。 每當新項目開始發射時,SwitchMap 都會取消訂閱前一個源 Observable,因此總是從當前 Observable 發射項目。
如果您想了解更多關於 rxjs 運算符的信息,請查看此處。
嘗試:
@Effect()
someEffect$ = this.actions$.pipe(
ofType(someAction: Actions),
switchMap(
(action)=>{
return this.authService.getProfile(action.payload.authInfo).pipe(
map((response: any) => {
if (response.isErrorResponse) {
return [new HeaderActions.AuthFail(response)];
} else {
//here i'd like to return multiple actions
return [
new HeaderActions.FetchMPInfoSuccess(this.fetchMpInfoSuccesState(getMpProfileResponse)),
new HeaderActions.GetAccountStates(true)
]
}
}),
catchError((error:HttpErrorResponse )=>{
return of(new HeaderActions.AuthFail(response));
})
);
}
)
);
所以基本上我所做的是,我沒有在服務調用之前使用mergeMap
,而是將它換回了簡單的switchMap
。
我從mergeMap
更改它的原因是:您只從單個 stream 返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.