【问题标题】:Angular RXJS 6: filter observable array for items matching object keyAngular RXJS 6:过滤与对象键匹配的项目的可观察数组
【发布时间】:2020-11-24 20:41:15
【问题描述】:

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

如果我有一个国家/地区的 3 字母代码,我希望能够过滤 observable 并返回匹配的名称。例如,如果我有“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 返回一个 observable,name 接收一个 observable。
  • 所以我尝试这个仍然什么都没有` const name = this.countries$.pipe(filter((c) => c.alpha3 === 'GBR')).subscribe((x) => console.log(x));`
  • console.log(x) 应该显示您正在寻找的结果.....

标签: angular filter observable rxjs6


【解决方案1】:

Filter 在您的情况下返回一个 observable,它被分配给 name;

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'));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多