【问题标题】:Angular 8: filter results from an RxJS observable (from Angular.io tutorial)Angular 8:过滤来自 RxJS observable 的结果(来自 Angular.io 教程)
【发布时间】:2020-06-11 17:19:49
【问题描述】:

在 Angular.io 教程(“Tour of Heroes 应用程序”)中,他们使用此代码从服务返回一组对象:

https://angular.io/tutorial/toh-pt6#tap-into-the-observable

/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap(_ => this.log('fetched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
}

但是,如果您需要返回一个带有单个结果的可观察对象,他们假定 API 提供了该服务(即,API 采用 id 参数) .

但是,如果您希望您的 服务 采用 id 参数,然后 过滤上面的函数:

例如,在伪代码中:

getHero(id: number): Observable<Hero> {
  // call getHeroes (as above)
  // filter the results to return only the here who's id property matches the id parameter;
  this.getHeroes().[filter this somehow, and return an observable with just the match]
}

你是怎么做到的?

提前抱歉 - 我在这里发现了类似的问题,但是它们要么依赖于旧版本的 Angular/RxJS,要么不完全符合本教程(例如,函数返回数组而不是 observable。 ..)

【问题讨论】:

    标签: angular rxjs angular8


    【解决方案1】:

    这是一个映射函数 - 您正在获取某个形状的对象(n 个结果的数组),并希望将其映射到另一个形状的对象(单个对象)。

    为此,您可以在管道中使用map 运算符。

    getHero(id: number): Observable<Hero> {
      return this.getHeroes().pipe(
        map(heroes => heroes.find(x => x.id === id))
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 2018-06-14
      • 2018-07-26
      • 1970-01-01
      相关资源
      最近更新 更多