如何使用 rxjs 链接多个 .map() 对先前项目的调用

How to chain multiple .map() calls on previous items using rxjs

在下面的示例中,我想知道您将如何对来自 .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));

对于这个答案,我假设函数 userCourse.LoadUserCourseSuccessActioncourse.LoadCourseSuccessAction 都执行 return Observables。如果没有,您总是可以使用 Rx.Observable.ofRx.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));

Runnable demo