0
votes

In my Angular app I have a component where I'm loading a grid view of some data being returned from the API. I also have some filters on the component, that the user can make use of to filter the data being returned.

This all works as expected -- until the user navigates away, and then returns to the component. At that point the filter selections are no longer being applied. In other words, the component is re-loaded in its "virgin" state, as if no filters had been selected.

So what I think I need to do is use ngOnInit() to read the url state from the browser window -- since all of the filters are still there at this point, as part of the query string, like so:

http://localhost:4200/consulting;page=1;pn_firstName.e=1;pn_firstName.v=John;pn_lastName.e=;pn_lastName.v=

According the above url/query string, the data should load after filtering on "firstName":"John".

So, my question is, what does the syntax look like in Angular to pre-load from the url like this within ngOnInit? Something like this?

ngOnInit() {
   this.router.navigateByUrl(`consulting/${}`); // Should be current url/query string in the browser window
}

Basically I just need to know what the syntax should look like when I want this to be read dynamically from the current state of the url/query string in the browser window. Because, that way, whatever filters had been applied will work accordingly upon re-load of the component -- because they're still available in the query string.

UPDATE:

After a comment below, I'm thinking I could do something like this:

constructor(private route: ActivatedRoute) {}

And then, because this is an observable, I'd do something like:

ngOnInit() {
    this.loadData()
}

loadData() {
    this.router.navigate([this.route.queryParams.toArray()]);
}

Will something like this work?

1

1 Answers

1
votes

Inject activatedRoute: ActivatedRoute into your component and the query params are available either through activatedRoute.queryParams or activatedRoute.queryParamMap.

See the docs about router.

Here is simple stackblitz demo which just renders the query params and you can play with the query parameters here.