首页 > 解决方案 > 如何使用另一个 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

标签: rxjs

解决方案


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

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()
        );

推荐阅读