角度激活的路由参数映射为空,具体取决于我在提供程序中指定服务的位置



我正在使用 ActiveRoute 从注入服务中的路由中获取参数。 如果我在应用程序模块或应用程序组件中将服务指定为提供程序,则参数映射在调用时为空。 如果我在拉入服务的组件中将其指定为提供程序,则它具有参数。

为什么会这样工作。 我很难找到有关激活路由的范围以及它如何与服务交互的好信息。

链接到 plnkr 中的此行为。 取消注释 a.component.ts 中的第 11 行(提供者字段),以便在您单击我时查看它是否正常工作! https://plnkr.co/edit/3U9dZm9fdUlG6KW3GyoQ

import {Component, OnInit} from '@angular/core'
import {AService} from './a.service.ts'
@Component({
selector: 'app-a',
template: `
<div>
<h2>Hello {{id}}</h2>
</div>
`,
//  providers: [AService]
})
export class AComponent implements OnInit {
id: string;
constructor(private aService: AService) {
}
ngOnInit() {
this.id = this.aService.getId();
}
}

您看到的行为是由于激活路由中paramMap成员的性质造成的。在您的服务构造函数中,您订阅了 paramMap

constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.paramMap.subscribe(
params => {
this.id = params.get('id');
}
);
} 

这将生成其关联组件的路由的SnapShot视图。此时,由于您将a.service.ts声明为根模块的提供者app.module.ts路由的快照将不包含:id,因为它关联的组件是您app.component.ts。因此,当您调用方法

getId(): string {
return this.id;
}

从组件中,您会收到与app.component.ts关联的路由的初始快照,并且不包含值。

但是,当您将a.service.ts声明为组件的提供者时a.component.ts您已经创建了a.service.ts的新本地实例。 在此方案中,对paramMap所做的订阅与a.component.ts相关联,并且该组件路由的快照确实包含:id参数,因此在调用getid()时会返回给您。

从 Angular 源代码:

export class ActivatedRoute {
/** The current snapshot of this route */
_paramMap: Observable<ParamMap>;
...}

>

最新更新