将 observable 映射到另一个 promise observable 列表

Mapping obsevable to another list of promise observable

这是我正在尝试做的事情: 我有来自 api 的口袋妖怪。 pokeapi http 响应是对象列表,仅包含名称和 url 属性。 我需要将这些 url 映射到可观察的值。我基本可以用

    Promise.all(...).then(data => observable$.next(data))

但这对我来说似乎不够优雅, 这是我的尝试

    const __URL__ = 'https://pokeapi.co/api/v2/pokemon/';
    const pokemon$ = from(
        fetch(__URL__)
            .then((res) => res.json())
            .then((res) => res.results)
    );
    
    var pokemons$ = new BehaviorSubject([]);
    pokemon$.subscribe((pokes) => {
        Promise.all(pokes.map((p) => fetch(p.url).then((res) => res.json()))).then((pokks) =>
            pokemons$.next(pokks)
        );
    });

我只是想知道是否有一种方法可以使用 observable operators(map) 优雅地生成具有单个 observable 的结果。

您可以使用 forkJoin 函数实现,如下所示:

// import { BehaviorSubject, forkJoin, from } from 'rxjs';
// import { mergeMap } from 'rxjs/operators';

const __URL__ = 'https://pokeapi.co/api/v2/pokemon/';
const pokemon$ = from(
  fetch(__URL__)
    .then((res) => res.json())
    .then((res) => res.results as Array<{ name: string; url: string }>)
);

const pokemons$ = new BehaviorSubject([]);
pokemon$
  .pipe(
    mergeMap((pokes) =>
      forkJoin(
        pokes.map((poke) => from(fetch(poke.url).then((res) => res.json())))
      )
    )
  )
  .subscribe((pokks) => pokemons$.next(pokks));