Angular RXJS 6:过滤与对象关键字匹配的项目的可观察数组



我有一个服务,它返回一个对象数组作为可观察对象,一个带有国家名称和三个字母代码的对象的国家列表,countries$ = this.mockData.get('countries.json');

如果我有一个国家的3个字母的代码,我希望能够过滤可观察到的内容并返回匹配的名称。例如,如果我有";GBR";我想返回";大不列颠及北爱尔兰联合王国";

我试过了,

getfullCountryName() {
const name = this.countries$.pipe(filter((c) => c.alpha3 === 'GBR'));
console.log('name =', name);

return name;
}

但我一定忘了什么,因为我在控制台里得到的只是name = Observable {_isScalar: false, source: Observable, operator: FilterOperator}

我要做什么?

countries$是Country 的一种

export interface Country {
numeric: string;
alpha2: string;
alpha3: string;
name: string;
}

我应该把类型< >放在那个表达式中的哪个位置以获得打字员。例如c具有属性alpha3

Filter在您的情况下返回一个可观察,该结果被分配给名称

getfullCountryName() {
const name = this.countries$.pipe(filter((c) => c.alpha3 === 'GBR'));

return name;  // returns observable
}

某处

this.getfullCountryName().subscribe(result=>console.log(result));  // will print the right result.

更好的版本,
getfullCountryName() {
return this.countries$.pipe(filter((c) => c.alpha3 === 'GBR'));
}

最新更新