【问题标题】:Chaining rxjs 6 observables链接 rxjs 6 个 observables
【发布时间】:2019-11-26 19:12:38
【问题描述】:

我必须创建一个 ajax 请求队列并对结果进行分组,但我不知道如何完成此操作。

假设我有一个这样的数组:

const actors = [
  "Al Pacino",
  "Robert De Niro"
];

我必须对其进行迭代,并为每个值进行 api 调用:

export const getMovies = action$ =>
  action$.pipe(
    ofType(LOAD_REQUEST),
    // iterate over the array
    // make api call with the actor name
    // for each result, make a second api call with the id of the actor (get in the response.results.id)
    // group the result in an array with all films of all actors of the array passed in the payload
  );

我被 switchMap、pipe ... 卡住了,不知道完成此操作的正确方法。

编辑尝试了您的解决方案 Valeriy,但收到此错误:

export const getMovies = action$ =>
  action$.pipe(
    ofType(LOAD_REQUEST),
    switchMap(({ payload }) =>
      combineLatest(
        payload.map(a => {
          return ajax
            .getJSON(actor(a))
            .pipe(map(response => console.log(response)));
        })
      )
    )
  );


TypeError: You provided 'function (source) {
    return source.lift.call(Object(_observable_from__WEBPACK_IMPORTED_MODULE_2__["from"])([source].concat(observables)), new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__["CombineLatestOperator"](project));
  }' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

【问题讨论】:

    标签: rxjs redux-observable


    【解决方案1】:

    如果我对您的理解正确,您正在尝试实现这样的目标:

    export const getMovies = action$ => action$.pipe(
        ofType(LOAD_REQUEST),
        switchMap(() => {
            // group the result in an array with all films of all actors of the array passed in the payload
            return combineLatest(
                // iterate over the array
                ...actors.map(actorName => {
                    // make api call with the actor name
                    return loadActor(actorName).pipe(
                        // for each result, make a second api call with the id of the actor (get in the response.results.id)
                        switchMap(response => loadActorFilms(response.results.id))
                    );
                })
            );
        })
    );
    

    我使用combineLatest 将多个可观察对象组合在一起。

    【讨论】:

    • 我尝试了您的解决方案但出现错误,我编辑了我的答案
    • @amerej 我猜这是因为combineLatest() 需要一个可观察的数组作为输入,但最后一个映射map(response => console.log(response)) 转换了输出类型。如果您只想记录结果,请使用tap 而不是map
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2017-01-06
    • 2016-09-07
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多