将可观测映射到另一个可观测承诺列表



下面是我要做的:我有来自api的pokemons。pokapihttp响应是对象列表,只包括名称和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)
);
});

我只是想知道有没有一种方法可以使用可观察算子(map(优雅地生成具有单个可观察的结果。

您可以使用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));

最新更新