I am trying to get my activatedRoute in my Angular app, so that I can load this within the onInit life cycle hook, so that when a user returns to a component, the component will load with the state of the url as they last left it.
I have already imported activatedRoute and am injecting it in the constructor:
constructor(private route: ActivatedRoute) {}
Then, in onOnit, just to see what I have, I tried this:
console.log('route info: ', this.route.queryParams);
What I get back is a behavior subject
, so I try adding this:
console.log('route info: ', this.route.queryParams.toArray().subscribe());
This now returns a subscriber
.
Bottom line, what I want is to be able to capture the current url/query string, and load it up within ngOnInit. Something like this:
ngOnInit() {
this.loadData();
}
loadData() {
this.route.queryParams;
}
Does this look close? How can I actually get the component to use activatedRoute to load up what's in the url/query string?
UPDATE: After a suggestion below, I'm thinking it could look something like this?
ngOnInit() {
this.loadData();
}
loadData() {
let currentRoute = this.route.params.subscribe(params => {
// logic goes here
console.log(params['firstName']);
return params;
});
this.router.navigate([currentRoute]);
}
UPDATE 2:
If I do this:
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
let myParams = params;
console.log(myParams);
});
}
I get this back in the console:
{pn_firstName.e: "1", pn_firstName.v: "John"}
And this is what my url/query string looks like:
http://localhost:4200/consulting;pn_firstName.e=1;pn_firstName.v=John
So it does seem to be getting the query string from what I can see in the console.
So, bottom line, will this load up the current state of the url/query string when the component loads?
ngOnInit() {
let currentRoute = this.activatedRoute.params.subscribe((params: Params) => {
let myParams = params;
console.log(myParams);
return myParams;
});
this.router.navigate([currentRoute]);
}
Apparently, not, because this is what I get for the url when loading the component:
http://localhost:4200/consulting;closed=false;_parent=null;_parents=null;_subscriptions=%5Bobject%20Object%5D;syncErrorValue=null;syncErrorThrown=false;syncErrorThrowable=false;isStopped=false;destination=%5Bobject%20Object%5D
Your
loadData()
can look like following: