避免在Angular 2+中嵌套订阅? [英] Avoiding nesting subscriptions in Angular 2+?
问题描述
我有2个端点:
- 1个端点来记录当前用户.
- 1个端点来获得该用户的授权.
我实际上使用:
this.user
.subscribe((e) => {
this.grants.get(e)
.subscribe((x) => {
console.log(x)
})
})
但这是Angular 2 +/RxJS的反模式.
But this is an anti-pattern of Angular 2+/RxJS.
我想知道如何遵循Angular/RxJS最佳实践.
I would like to know how to do this following Angular/RxJS best practices.
谢谢
推荐答案
避免嵌套订阅取决于可观察对象的性质以及它们如何相互依赖:
Avoiding nested subscriptions depends on the nature of the observables and how they depend on each other:
当可观察对象( this.grants.get()
)依赖于另一个可观察对象( this.user
)的通知时,可以使用任何更高版本的RxJS订单映射运算符 switchMap
, mergeMap
, concatMap
和 exhaustMap
.每个人都有自己的目的.您可以在此处找到它们之间的区别.
When an observable (this.grants.get()
) depends on the notification from another observable (this.user
), you could use any of the RxJS higher order mapping operators switchMap
, mergeMap
, concatMap
and exhaustMap
. Each has their own purpose. You could find the differences between them here.
他们之间的简短差异
-
switchMap
-如果外部可观察到的发射,则取消内部可观察到的 -
mergeMap
-触发每个外部通知的内部观察(展平外部通知) -
concatMap
-本质上是mergeMap
,可以随时具有单个并发请求(展平外部通知,但按顺序发出) -
exhaustMap
-如果内部可观察项尚未完成,则忽略外部通知
switchMap
- cancel inner observable if the outer observable emitsmergeMap
- trigger inner observable for each outer notification (flatten the outer notifications)concatMap
- essentiallymergeMap
with single concurrent request at any time (flattens the outer notifications but emit them in order)exhaustMap
- ignore outer notifications if inner observable hasn't completed
使用 switchMap
运算符
this.user.pipe(
switchMap(e => this.grants.get(e))
).subscribe((x) => {
console.log(x)
});
独立的可观察物
如果可观察对象彼此独立,则可以使用RxJS函数(例如 forkJoin
, combineLatest
或 zip
)并行触发可观察对象
Independent observables
If the observables are independent of each other, you could use RxJS functions like forkJoin
, combineLatest
or zip
to trigger the observables in parallel.
他们之间的简短差异
-
forkJoin
α-仅在所有可观察项完成时发出 -
combineLatest
α,β-当任何个可观察对象发出时发出(不包含任何可观察到的可观察对象将发出旧值) -
zip
α,β-在所有所有可观察物发射时发射
forkJoin
α - emit only when all the observables completecombineLatest
α,β - emit when any of the observables emit (observables w/o emissions will emit old value)zip
α,β - emit when all of the observables emit
使用 forkJoin
forkJoin(this.obs1, this.obs2, ...).subscribe(
res => console.log(res)
);
α-从每个可观察对象发出一系列通知(例如,(this.obs1,this.obs2,...)
将发出 ['res from obs1","res from obs2",...]
).
α - emits an array of notifications from each observable (eg. (this.obs1, this.obs2, ...)
will emit ['res from obs1', 'res from obs2', ...]
).
β-所有可观察物应该至少发射一次,以供操作员发射
β - all observables should emit atleast once for the operator to emit
这篇关于避免在Angular 2+中嵌套订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!