这是我的问题。
假设我有一个带有国家/地区清单的可观察物,而另一个可观察物根据一个键返回了推导。
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
答案 0 :(得分:0)
您可以执行以下操作:
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()
);