问题
I'd like to wait for the two http requests below to finish before triggering another action. However, the http requests were not fired. Only the DASHBOARD_INIT action was triggered:
export const dashboardInitEpic = (action$: any) =>
action$.ofType(InitActionTypes.DASHBOARD_INIT)
.switchMap((action: ActionDashboardInit) =>
zip$(
of$(fetchConfig(action.payload)),
of$(fetchPermission(action.payload))
).switchMap(() =>
zip$(
action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED).take(1)
).switchMap(() => of$({type: InitActionTypes.DASHBOARD_INIT_COMPLETE}))
)
);
To get the http requests fired, I had to do the following which is not exactly what I want. Concat forces the http requests to be in sequence and the code below listens to FETCH_CONFIG_FULFILLED and FETCH_PERMISSION_FULFILLED in sequence, which breaks sometimes depending on whether fetchConfig's response comes back first.
export const dashboardInitEpic = (action$: any) =>
action$.ofType(InitActionTypes.DASHBOARD_INIT)
.mergeMap((action: ActionDashboardInit) =>
concat$(
of$(fetchConfig(action.payload)),
of$(fetchPermission(action.payload)),
action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED)
.take(1)
.switchMap(() => of$({type: InitActionTypes.DASHBOARD_INIT_COMPLETE}))
)
);
Any help is greatly appreciated. Have been stuck on this for a few days. Thanks a lot!
回答1:
Try this:
export const dashboardInitEpic = (action$: any) =>
action$
.ofType(InitActionTypes.DASHBOARD_INIT)
.mergeMap((action: ActionDashboardInit) =>
concat$(
of$(fetchConfig(action.payload)),
of$(fetchPermission(action.payload)),
zip$(
action$.ofType(ActionTypes.FETCH_CONFIG_FULFILLED).take(1),
action$.ofType(ActionTypes.FETCH_PERMISSION_FULFILLED).take(1)
).mapTo({ type: InitActionTypes.DASHBOARD_INIT_COMPLETE })
)
);
来源:https://stackoverflow.com/questions/50951633/redux-observable-how-to-wait-for-multiple-async-requests-then-perform-action-in