如何使用另一个Observable的值操作Observable中的项目列表



这是我的问题。

假设我有一个带有国家列表的可观察项,另一个可观察项根据键返回一个交易。

interface CountryCode {
id: number;
code: string;
}
interface Country implements CountryCode {
name: string;
}
public getCountries():Observable<CountryCode[]>{
return Observable.of([{id:1,code:'fr'},{id:2,code:'en'}];
}
public getTrad(key: string):Observable<string> {
const trad = {fr: 'France',en: 'Angleterre'};
return Observable.of(trad[key]);
}

我该怎么做才能在最后拥有:

[{id:1, name:'France', code:'fr'},{id:2, name:'Angleterre', code:'en'}]

我的麻烦在于处理第二个可观察到的。

const countries$: Observable<Country[]> = this.getCountries()
.map(items => items.map(
item => assign(item, {name: this.getTrad(item.code)}))); //wont work

这不起作用,因为我有ScalarObservable

您可以按如下方式执行此操作:

import { flatMap, mergeMap, toArray } from 'rxjs/operators';
const countries$: Observable<Country[]> = this.getCountries()
.pipe(
// flatten the array in order to operate with the singular elements
// note that `flatMap` is just an alias for `mergeMap`
flatMap(countryCodes => countryCodes),
// combine the source observable, a country code, with 
// another observable
mergeMap(countryCode => this.getTrad(countryCode.code)
.pipe(map(name => ({name, ...countryCode})))),
// collect the single elements into a new array
toArray()
);

最新更新