下面是我的代码段。我想知道为什么它从未遇到完成处理程序吗?我想做的是,首先调用serviceA来获取具有给定路由参数['key']的objectA,然后调用serviceB来获取objectB。因此,objectB取决于objectA的结果,而objectA的结果取决于给定的param ['key']。
ps.s。我正在将Angular 7与rxjs6一起使用
ngOnInit() {
this.route.params.pipe(
mergeMap(
(params: Params) => {
this.key = params.key;
return this.serviceA.getObjectA(this.key); // http request service to backend
}
),
mergeMap(
(objectA: ObjectA) => {
// do something with objectA
return this.serviceB.getListOfObjectB(); // http request service to backend
}
)
).subscribe(
(objectBList: ObjectB[]) => {
for (const b of objectBList) {
// do something with objectB
}
// the code execution ends here
},
() => {
// error handler
},
() => {
// completion handler
// the code execution NEVER comes to here, WHY??
}
);
}
ngOnDestroy
中退订。如果需要订阅的观察对象不止一个,请使用另一种方法。最灵活的方法是:
private _destroy$: Subject<void> = new Subject<void>();
...
ngOnInit() {
this.route.params.pipe(
...,
takeUntil(this._destroy$)
).subscribe(
(objectBList: ObjectB[]) => {...},
() => {// error handler},
() => {// completion handler}
);
}
ngOnDestroy() {
if(this._destroy$ && !this._destroy$.closed) {
this._destroy$.next();
this._destroy$.complete();
}
}