0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I added some code as a follow-up above, but I think I'll update it to look more like what you have in your example.
When I try and use ParamMap, it's not finding it. Is this available in Angular 2?
No it is not. It is available in angular 4+.
But you can use queryParams in Angular 2. queryParamMap is just new and preferred way to access the query params.
Yes, I think you can use queryParams in Angular 2.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.