Matt Downey
Matt Downey

Reputation: 393

re-resolving data upon query parameter change?

In my angular 2 projects, I wasn't able to reload the page by navigating to the same URL but with different query params. I am using resolve to pre-fetch data upon loading the page.

I am trying to get the resolver to re-fetch the data when there's URL (query param) change. How do I do this?

Upvotes: 12

Views: 5292

Answers (2)

GautierDab
GautierDab

Reputation: 481

Now you can with this in your route config:

{
  path: '',
  resolve: {
    data : DataResolver,
  },
  runGuardsAndResolvers: 'paramsOrQueryParamsChange',
  component: MainComponent
}
 

Passing the 'paramsOrQueryParamsChange' in your route config will trigger the DataResolver at each params or queryParams change.
you can get the resolvers data in your MainComponent like this:

ngOnInit() {
  this.activatedRoute.data.subscribe((resolversData) => {
     // is now triggered at each queryParams change
  })
}

see the doc for more info

Upvotes: 32

noname
noname

Reputation: 271

I think you can't get changed queryParam. I don't know if this helps you but here is my answer.

construtor(private route: ActivatedRoute) { }

ngOnInit() {

  this.route.snapshot.queryParams['something'];//when you snapshot and navigate to same url you can't get new query params, only for first initialization

  // to get new queryparams or url params also you need subscribe (for same url navigation)

  this.route.queryParams.subscribe({
      (queryParams: Params) => {
          this.yourParam = queryParams['something'];  
      }
   })
}

I think you are using snapshot instead of Observable queryParams thats why.

Upvotes: 0

Related Questions