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?
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With