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

问题描述 投票:0回答:1

这是我的问题。

假设我有一个带有国家列表的观察者,另一个可观察者根据一个键返回一个转义。

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'}]

我麻烦它与第二个observable一起工作。

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

这不起作用,因为我有ScalarObservable

rxjs
1个回答
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()
        );
© www.soinside.com 2019 - 2024. All rights reserved.