我想获取Angular ActivatedRoute queryParams更改并仅执行一次功能,而每次执行其他功能。
到目前为止,我发现的方式是两次订阅,但是我想要一种更好的方式,也许使用一些pipe
运算符。
// DO SOMETHING THE FIRST TIME
this.activatedRoute.queryParamMap
.pipe(
first(),
switchMap(params => {
// HTTP CALL
})
)
.subscribe((data: any) => {
// DO SOMETHING
});
// DO SOMETHING ALWAYS
this.activatedRoute.queryParamMap
.subscribe((params: any) => {
// DO SOMETHING
});
还有其他方法吗,比如splitSubscription
运算符?
答案 0 :(得分:1)
一种方法可以是这样的,
visited = false;
this.activatedRoute.queryParamMap.pipe(
tap(_ => {
//do your always thing
}),
filter(_ => !this.visited),
tap(_ => {
this.visited = true;
// do your one time thing
})
).subscribe();
您可以拥有一套自己的运算符,而不是轻按,需要注意的是,以这种方式进行过滤将仅允许一次失败,并且可以进行一次实现。
答案 1 :(得分:0)
您可以重构一下,而不是尝试多次订阅activatedRoute.queryParamMap
-不确定您要查询的拆分运算符是否可能。以下模式是非常标准的
// Class properties
private paramMapSubject = new BehaviourSubject<ParamMap>(null);
// Using a public observable if your binding to components, or exposing in a service
public params$ = this.paramMapSubject.asObservable();
// In your constructor
// componentDestroyed$ is a subject that's nexted in ngOnDestroy
this.activatedRoute.queryParamMap
.pipe(
takeUntil(componentDestroyed$)
tap( params => {
this.paramMapSubject.next(params)
}),
)
.subscribe();
// In ngOnInit - will only be called once - if it's in a component
this.params$.pipe(
takeOne(),
tap( params => {
// Do Something Once
}).subscribe()
this.params$.pipe(
takeUntil(componentDestroyed$)
tap( params => {
// Do Something continuously
}).subscribe()