首页 > 解决方案 > 在 Angular rxjs 服务中,如何从 HttpClient.get 的返回对象的属性中返回一个 observable

问题描述

在角度服务中,我希望该方法返回数据的属性而不是所有数据。

我试过这个:

export class RecipeService {

  private recipesUrl = 'http://localhost:8081/recipes';

  constructor(private http: HttpClient) { }

  getRecipes (): Observable<Recipe[]> {
    return this.http.get<Recipe[]>(this.recipesUrl).pipe((data) => {
       return of(data['recipes']);
    });
  }

}

标签: angularrxjs

解决方案


你可以试试pluck运算符。

getRecipes (): Observable<Recipe[]> {
    return this.http
        .get<Recipe[]>(this.recipesUrl)
        .pipe(pluck('recipes'));
}

推荐阅读