激活的路由在服务的构造函数中未定义
Actived Route is undefined in service's constructor
有一项服务 trackUrlService
导入到 CoreModule
export class TrackUrlService implements OnDestroy {
...
constructor(private router: Router, private route: ActivatedRoute) {
...
this.subs.add(
this.route.params.subscribe((params: Params) => {
console.log(params.workflowId); // output: undefined
...
})
);
}
...
有一个组件DummyComponent
ngOnInit() {
this.subs.add(
this.trackUrl.currWorkflowId.subscribe(currWorkflowId => {
console.log(currWorkflowId); // output: undefined
}),
...
/* this.route.params.subscribe(params => {
console.log(params.workflowId) // output: 391 (correct)
}), */
...
问题:
为什么从服务的构造函数输出 undefined
调用 this.route.params
?
但是从组件的 ngOnInit()
调用 this.route.params
有效并输出正确的值。
来自 ActivatedRoute
文档:"Provides access to information about a route associated with a component that is loaded in an outlet",即 ActivatedRoute
params
仅在路由组件内部可见。
有一项服务 trackUrlService
导入到 CoreModule
export class TrackUrlService implements OnDestroy {
...
constructor(private router: Router, private route: ActivatedRoute) {
...
this.subs.add(
this.route.params.subscribe((params: Params) => {
console.log(params.workflowId); // output: undefined
...
})
);
}
...
有一个组件DummyComponent
ngOnInit() {
this.subs.add(
this.trackUrl.currWorkflowId.subscribe(currWorkflowId => {
console.log(currWorkflowId); // output: undefined
}),
...
/* this.route.params.subscribe(params => {
console.log(params.workflowId) // output: 391 (correct)
}), */
...
问题:
为什么从服务的构造函数输出 undefined
调用 this.route.params
?
但是从组件的 ngOnInit()
调用 this.route.params
有效并输出正确的值。
来自 ActivatedRoute
文档:"Provides access to information about a route associated with a component that is loaded in an outlet",即 ActivatedRoute
params
仅在路由组件内部可见。