Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

angular2 routing - Angular 2.0.2: ActivatedRoute is empty in a Service

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

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

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.

Component (test is retrieved):

export class Component implements OnInit {
  result: string;

  constructor(private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.result = params['test'];
    });
  }
}

Service (test is not retrieved):

export class Service {
  result: string;

  constructor(private route: ActivatedRoute) {
    this.getData();
  }

  getData() {
    this.route.params.subscribe(params => {
      this.result = params['test'];
    });
  }
}
question from:https://stackoverflow.com/questions/39977962/angular-2-0-2-activatedroute-is-empty-in-a-service

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Outlets get their own injector and own ActivatedRoute instance.

The solution here is to let route components have their own Service instances:

@Component({
  ...
  providers: [Service]
})
export class MainComponent { ... }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...