在下面的示例中,我想知道如何对 .swichMap() 的同一响应执行两个操作。
在示例中,我放置了第二个 .map,其中显然是错误的,但有点不识字我想要做什么。我将如何调用两个函数。另外,当我将第一个 map() 分解为 .map(response => {fn1; fn2;}); 之类的函数时 typescript 抛出错误?
@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));
最佳答案
对于这个答案,我假设两个函数 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));
关于javascript - 如何使用 rxjs 对先前的项目链接多个 .map() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894691/