使用 api 调用设置可观察对象的 属性

set property of an observable object with an api call

我有一个类似下面的服务功能。


getByIdWithCategory(id: number): Observable<Product> {

    const category = new Category();
    category.name = 'sample category';

    return this.httpClient.get<Product>(this.baseUrl + `/${id}`)
      .pipe(map(product => ({...product, category})));
  }

我通过模板文件中的异步管道从此处获取返回值。但我需要从 api 中获取类别。我需要订阅这个。但是我不能取消订阅。这方面的最佳做法是什么?

下面的函数正是我想要的。但是我找不到取消订阅 api 电话的方法,我从中获得了类别。

  getByIdWithCategory(id: number): Observable<Product> {

    return this.httpClient.get<Product>(this.baseUrl + `/${id}`)
      .pipe(
        tap(product => {
          this.categoryService.getById(product.id)
            .subscribe(category => {
              product.category = category;
            });
        })
      );
  }

这是我的产品 class。

export class Product {
  id: number;
  title: string;
  price: number;
  description: string;
  categoryId: number;
  image: string;

  category: Category;
}

尽量避免嵌套订阅。在 tap 运算符内部进行订阅看起来特别不雅。相反,您可以使用 switchMap 从一个 observable 映射到另一个。并将 map 传递给内部可观察对象,并使用 category 属性.

return 整个对象

尝试以下方法

getByIdWithCategory(id: number): Observable<Product> {
  return this.httpClient.get<Product>(this.baseUrl + `/${id}`).pipe(
    switchMap((product: Product) => {
      this.categoryService.getById(product.id).pipe(
        map((category: Category) => ({
          ...product,
          category: category
        }))
      )
    })
  );
}