Angular 2.0.2:Serviced中的ActivatedRoute为空 [英] Angular 2.0.2: ActivatedRoute is empty in a Service

查看:72
本文介绍了Angular 2.0.2:Serviced中的ActivatedRoute为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ActivatedRoute在服务中获取路由参数,就像在Component中一样. 但是,当我在服务中注入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

我创建了一个重现此行为的插件: http://plnkr.co/edit/sckmDYnpIlZUbqqB3gli

I've created a plunker that reproduces the behaviour: http://plnkr.co/edit/sckmDYnpIlZUbqqB3gli

请注意,其目的是在服务中而不是在组件中使用参数,punker的设置方式纯粹是为了演示问题.

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这是一个属于根注入器的单例,并通过

Service here is a singleton that belongs to root injector and is injected with root ActivatedRoute instance.

插座有自己的进样器,并且拥有自己的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:Serviced中的ActivatedRoute为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆