angular - 角度项目中的 Observables (rxjs) 嵌套订阅
问题描述
有什么更好的选择来简化下面的嵌套代码?该代码确实有效,但我确实知道嵌套订阅并不是我所读到的。我也不确定在这个特定示例中是否应该使用 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”,我猜这是等待进程完成的黑客行为。
推荐阅读
- python - windows脚本重新排序和替换xml文件中的文本?
- animation - 从 fbx 模型构建骨架
- python - python中的p值调整Mann-Whitney U检验
- java - 代码神秘地运行两次后TextsView null
- sql - 获取分配有多个连接条件的重复值
- javascript - `ckeditor` 文件上传问题
- spring-batch - 使用 Java config 进行分区作业配置
- java - Java - 询问用户是否要继续(仅接受“y”或“n”)
- ios - 如何发送 click_action Firebase 通知。(迅速)
- javascript - 使用 onclick 更改两个值