【发布时间】: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。 ..)
【问题讨论】: