angular - 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);
}
);
});
解决方案
你可以像这样改变你的代码
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);
}
);
推荐阅读
- c++ - 在集合中存储相等的对象
- python - 尝试执行 for 循环以使网格中的元素彼此分开
- neo4j - 正确使用 UNWIND 和 COLLECT
- python - Django:在 Admin ListView 中更改列标题而不会失去可排序性
- html - CSS 逻辑属性和 Box-Shadow
- windows - 在 Windows 中为 Cortex-M4 交叉编译 Rust 项目
- javascript - Laravel Livewire 和谷歌图表
- python - 将自定义函数应用于熊猫数据框值
- linux - 更改 nginx 位置后,chown 无法在已安装的目录 docker 上工作
- javascript - 需要使用 javascript / node js 比较两个数组的替代代码