链接rxjs 6观测值

时间:2019-11-26 19:12:38

标签: rxjs redux-observable

我必须创建一个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,管道困住了,不知道实现此目的的正确方法。

编辑尝试解决您的解决方案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.

1 个答案:

答案 0 :(得分:3)

如果我对您的理解正确,那么您正在尝试实现以下目标:

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将多个可观察对象分组在一起。