rxjs - 如何使用另一个 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()
);
推荐阅读
- python - 如何获取具有模块加载的bash文件?
- r - 在 R 中使用 barplot 的图例格式和放置
- python - 在 matplotlib 插图中调整轴标签和轴边界之间的间距
- python - 不要将鼠标悬停在元素上并单击(python selenium)
- java - Java中的随机for循环?
- node.js - 在 docker 容器中运行 npm install 时,Docker 节点服务返回 ECONNRESET 网络错误
- django - 如何为用户登录编写测试用例
- php - PHP 7.4+ 中的“在初始化之前不能访问类型属性”错误
- db2 - 使用 Db2 在 select 语句中调用存储过程
- azure - 无法使用 ansible 加密 Azure 存储帐户