Angular 2.0.2:服务中的 ActivatedRoute 为空 [英] Angular 2.0.2: ActivatedRoute is empty in a Service
问题描述
我想使用 ActivatedRoute 来获取服务中的路由参数,就像我在组件中所做的那样.但是,当我在服务中注入 ActivatedRoute 对象时,它包含一个空的 params 变量
I want to use ActivatedRoute to get route params in a service like I would do in a Component. However, when I inject the ActivatedRoute object in a Service it contains an empty params variable
我创建了一个重现行为的plunker:http://plnkr.co/edit/sckmDYnpIlZUbqqB3gli
I've created a plunker that reproduces the behaviour: http://plnkr.co/edit/sckmDYnpIlZUbqqB3gli
请注意,目的是在服务中而不是在组件中使用参数,设置plunker的方式纯粹是为了演示问题.
Note that the intention is to use the parameter in the service and not in the component, the way the plunker is set up is purely to demonstrate the issue.
组件(检索test
):
export class Component implements OnInit {
result: string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe(params => {
this.result = params['test'];
});
}
}
服务(test
未被检索):
export class Service {
result: string;
constructor(private route: ActivatedRoute) {
this.getData();
}
getData() {
this.route.params.subscribe(params => {
this.result = params['test'];
});
}
}
推荐答案
Service
这里是一个单例,属于根注入器,注入root ActivatedRoute
实例.
Service
here is a singleton that belongs to root injector and is injected with root ActivatedRoute
instance.
Outlets 有自己的注入器和 自己的ActivatedRoute
实例.
Outlets get their own injector and own ActivatedRoute
instance.
这里的解决方案是让路由组件拥有自己的Service
实例:
The solution here is to let route components have their own Service
instances:
@Component({
...
providers: [Service]
})
export class MainComponent { ... }
这篇关于Angular 2.0.2:服务中的 ActivatedRoute 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!