我正在寻找一种比我现有的解决方案更具可读性的解决方案。
我需要:
1)从API检索产品。它们是objs数组。
2)根据类别等过滤那些产品...
3)对产品进行分页并返回这些产品的分页版本。
ngOnInit() {
//This gets the products from the API
this.drinkSubscription = this.drinkService.getAllDrinks().subscribe(drinks => {
//Save products without pagination for other purposes
this.allDrinks = drinks;
//Get the parameter to filter products
this.paramSubscription = this.route.params.subscribe((params: Params) => {
//Filter the products and return a filtered array
const filteredDrinks = this.filterService.filter(drinks, params['filter'], params['name']);
//Sort products based on the selection
this.sorterSubscription = this.sorter.initialize(filteredDrinks).subscribe(sortedDrinks => {
//Create a pager that holds the paginated drinks in a property
this.pagerSubscription = this.pagerService.initializePaginatedItems(sortedDrinks, 10, 5)
.subscribe(pager => {
this.pager = pager;
this.paginatedDrinks = pager.paginatedItems;
});
});
});
});
}
排序器和分页是BehaviorSubjects,因此我可以注入next(),但我对它们并不满意...
您可以看到缩进的级别很高,我想知道RxJS是否有一种方法可以更可读地获得相同的结果。
最佳答案
您应该能够使用运算符将它们组合在一起。我相信以下应该可行。
CombineLatest大致类似于Promise.all([p1,p2])
-仅当任何可观察对象发射时使用其他值使用之前的值发射。
switchMap允许您获取一个可观察对象发出的值,并将其映射到另一个可观察对象。
https://www.learnrxjs.io/operators/combination/combinelatest.html
https://www.learnrxjs.io/operators/transformation/switchmap.html
例如:
let drinkObservable = this.drinkService.getAllDrinks()
let paramsObervable = this.route.params
let sub = combineLatest(drinkObservable, paramsObervable)
.pipe(switchMap(([drinks, params]) => {
this.allDrinks = drinks
let filteredDrinks = this.filterService.filter(drinks, params['filter'], params['name']);
return this.sorter.initialize(filteredDrinks)
}))
.pipe(switchMap(sortedDrinks => {
return this.pagerService.initializePaginatedItems(sortedDrinks, 10, 5)
}))
.subscribe(pager => {
this.pager = pager;
this.paginatedDrinks = pager.paginatedItems;
})
关于javascript - RxJS:解开嵌套的可观察对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52408401/