首页 > 解决方案 > Angular 中的多个异步操作

问题描述

在一个 Angular 组件中,我正在处理三个或四个 Observable。我需要以某种方式对其进行重构,以避免这种写得很糟糕的代码带有丑陋的嵌套订阅调用。这很重要,因为您可以看到 productService 应该在 queryParamMap 之前调用,而对 categoryService 的调用并不重要。

我试图用 forkJoin 和 switchMap 重构它,但没有成功。

this.productService.getAll()
      .subscribe(
        (products: any) => {
          this.products = products;
          this.categoryService.getAll()
            .subscribe(categories => this.categories = categories);
          this.route.queryParamMap
            .subscribe(params => {
              this.category = params.get('category');

              if (this.category) {
                this.productService.getProductsByCategory(this.category)
                  .subscribe(fProducts => this.filteredProducts = fProducts);
              } else {
                this.filteredProducts = this.products;
              }
            },
              err => {
                console.log(err);
              }
            );
        });  

标签: angularangular8

解决方案


你可以像这样改变你的代码

this.productService.getAll()
.pipe(
    switchMap(products => {
        this.products = products;
        return this.categoryService.getAll()
            .pipe(
                map(categories => this.categories = categories)
            );
    }),
    switchMap(() => this.route.queryParamMap
        .pipe(
            switchMap(params => {
                this.category = params.get('category');
                return defer(() =>
                    (Boolean(this.category) ?
                     this.productService.getProductsByCategory(this.category) :
                     of(this.products)
                    )
                );
            })
        )
    )
)
.subscribe((filteredProducts) => {
        this.filteredProducts = filteredProducts;
    },
    err => {
        console.log(err);
    }
);

推荐阅读