Angular 8:过滤RxJS可观察到的结果(来自Angular.io教程)



在Angular.io教程("英雄之旅应用程序"(中,他们使用此代码从服务返回一组对象:

https://angular.io/tutorial/toh-pt6#tap-进入可观察的

/** 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的旧版本,要么它们不完全符合教程(例如,函数返回一个数组而不是一个可观察的…(

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

为此,可以在管道中使用map操作符。

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

最新更新