observable (rxjs)在angular项目中的嵌套订阅



简化下面嵌套代码的更好选择是什么?代码确实可以工作,但是我知道嵌套订阅并不好。我也不确定在这个特定的例子中是否应该使用mergeMap()或switchMap()。

private subscriptions: Subscription = new Subscription();
ngOnInit() {
this.subscriptions.add(this._route.paramMap.subscribe((paramMap: ParamMap) => {
if (this.docType === 'invoice' && paramMap.has('invoiceId')) {
this.mode = 'edit';
this.subscriptions.add(this._invoiceService.getInvoice(this.invoiceId).subscribe(invoiceData => {
//something here}));
}
else if (this.docType === 'quote' && paramMap.has('quoteId')) {
this.mode = 'edit';
this.subscriptions.add(this._quoteService.getQuote(this.quoteId).subscribe((invoiceData) => {//do something
}));
}
else {
//do something
this.subscriptions.add(this._route.params.subscribe(params => {
this.relatedProjectId = params['projectId']
}));
this.subscriptions.add(this._companyService.getCompany().subscribe(
res => {
this.showOwnCompany(res);
}
))
}
}
));
this.isOpen = true;
}

您可以删除路由paramMap订阅者,并使用解析器来替换整个初始化过程。

//someWork.resolver.ts

export class SomeWorkResolver implements Resolve<any> {
constructor(
private router: Router
private invoiceService: InvoiceService,
private quoteService: QuoteService
) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
if(route.param.has('invoiceId') {
return this.invoiceService.getInvoice();
} 
if(route.param.has('quoteId') {
return this.quoteService.getQuote();
} 
// implement the remainder
return EMPTY;
}
}

在你的路由器中添加:

{
path: 'somePath',
component: SomeComponent,
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
resolve: {
information: SomeWorkResolver
}
}

现在在实际的ngOnInit:

ngOnInit() {
// this has the information returned from the service call. 
// can you use this information to determine what call was made?
// IE Quote / Invoice / etc
this.router.snapshot.data.information;
}

这样做,也不会加载组件,直到解析器…解决了。所以也可以避免那句"this"。isOpen = true"我猜这是一个等待进程完成的hack。

最新更新