在下面的例子中,我想知道如何从.swichMap()对同一个响应执行两个操作。
在示例中,我将第二个.map放在其中显然是错误的,但有点文盲我想做什么。我怎么去调用两个函数。当我将第一个map()分解为像.map这样的函数时(response => {fn1; fn2;});打字稿会引发错误吗?
@Effect()
getUserCourse$: Observable<Action> = this.actions$
.ofType(userCourse.ActionTypes.LOAD_USER_COURSE)
.map<string>(action => action.payload)
.switchMap(userCourseId => this.userCourseApi.getUserCourse(userCourseId))
.map(response => new userCourse.LoadUserCourseSuccessAction(response.data));
.map(response => new course.LoadCourseSuccessAction(response.course));
答案 0 :(得分:2)
对于这个答案,我假设函数userCourse.LoadUserCourseSuccessAction
和course.LoadCourseSuccessAction
都返回Observables。如果不是,您可以随时使用Rx.Observable.of
或Rx.Observable.fromPromise
创建一个,例如AJAX调用。
如果我理解正确你想要对响应做独立的事情,但要并行执行并将结果合并回流中。请查看以下代码,了解如何归档。
Rx.Observable.of(
{data: 'Some data', course: 'course1'},
{data: 'Some more data', course: 'course2'}
).mergeMap((obj) => {
// These two streams are examples for async streams that require
// some time to complete. They can be replaced by an async AJAX
// call to the backend.
const data$ = Rx.Observable.timer(1000).map(() => obj.data);
const course$ = Rx.Observable.timer(2000).map(() => obj.course);
// This Observable emits a value as soon as both other Observables
// have their value which is in this example after 2 seconds.
return Rx.Observable.combineLatest(data$, course$, (data, course) => {
// Combine the data and add an additinal `merged` property for
// demo purposes.
return { data, course, merged: true };
});
})
.subscribe(x => console.log(x));