15

My form needs to access route params and data. They're observables so i need to subscribe to access their values. My question is, how do i access them both together in a single subscribe?

this._route.params.subscribe(
  params => {
    getData(params['id'], data['id2'] <=== i need data value too. how do i get this???)
  });

Why does angular put them in 2 separate observables?

2 Answers 2

17

how do i access them both together in a single subscribe?

You could use ActivatedRouteSnapshot from your ActivatedRoute. ActivatedRouteSnapshot interface has params and queryParams property, and you could get the both value at the same time.

Don't try to inject ActivatedRouteSnapshot directly. It won't work. You must inject ActivatedRoute and access its snapshot property.

Note: We only get the initial value of the parameters with this technique

constructor(private _route: ActivatedRoute) {
    console.log(this._route.snapshot.params);
    console.log(this._route.snapshot.data);
}

Example Plunker

Another way, since params and data are observable, we could use zip operator to merge them, then access them in a single subscribe. But be aware that if one of params or data do not have value, then the subscribe will not be triggered.

this._route.params
  .zip(this._route.data)
  .subscribe((value) => {
    this.id = value[0]["id"]; // get param
    this.data = value[1]; // get data value
  });

Example Plunker

Why does angular put them in 2 separate observables?

I have read the documentation, and you are correct,there are in separate observables, but I do not know why.

3
  • 1
    according to angular docs, they do. this._route.params.subscribe and this._route.data.subscribe
    – Reynaldi
    Commented Nov 13, 2016 at 10:00
  • @Reynaldi yeah you were correct. I was wrong. Sorry, I should read the documentation more often.
    – Michael
    Commented Nov 18, 2016 at 6:45
  • Do we also need to unsubscribe from this subscription made, in ngOnDestroy() hook? Commented Dec 14, 2021 at 11:33
12

Similar to Michael's response, you can use an ActivatedRouteSnapshot from your ActivatedRoute to get the route's data.

You can put this in a params subscription and it will be triggered even if the route does not contain any params.

this.route.params.subscribe((params) => {
  console.log(params);
  console.log(this.route.snapshot.data);
});
1
  • 1
    Note that params is a BehaviorSubject, so it keeps a value internally. Therefore subscribing will always immediately provides a value. (Yes this implementation could change but I doubt it) Commented Aug 21, 2018 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.