I have recently stared Angular and while learning on how we can navigate using Routes I had an issue on how to send Objects (not just strings) over routes, then I've came across NavigationExtras.state. I'm trying to send a query parameter as key-value pair and it was working fine. I was passing the query to the state and navigating using navigateByUrl and at the component, I'm retrieving the data from paramMap
this.router.navigateByUrl('/search', {state: {searchQuery: this.query}});
At the component:
ngOnInit() {
this.activatedRoute.paramMap.pipe(
map(() => window.history.state)
).subscribe(result => {
console.log('searchComponent: ' + result.searchQuery);
this.query = result.searchQuery;
});
}
Now the problem I'm facing is when I try to pass in a new query while I'm on the same route (that is '/search') it's not working. I've read about it online and came to know that if activeRoute doesn't change then the page/component won't be loaded again and we can force reload the component, but in my case, It is entering in an infinite loop call on the API. Is there a way to get the data from the State without reloading the component and make a new service call with that query to fetch the results? Can anyone help me understand how we can approach this issue?
Thanks
Edit: Here I'm using NavigationExtras.state because my data is not necessarily a key-value pair it can also be an object(for now it is just a simple query so it's just a key-value pair it can change in future so I'm using state).
Everything works fine the first time, what I mean is that I'm able to send data through state and get it at the search-Component and perform the search operation to retrieve the data from the server. So here I have the search input where I'm entering my query. Once I perform the search Operation my page is navigated to /search so when I try to enter another query to do the same again while I'm still on /search it won't work because If your navigate() doesn't change the URL that already shown on the address bar of your browser, the router has nothing to do. So what I'm trying now is how can I refresh the component/page if the query changes and also is there a way to get the new data without refreshing the component.
Edit 2:
this.navigationSubscription = this.router.events.subscribe((e: any) => {
console.log("instance of e", e)
if (e instanceof NavigationEnd) {
this.initialiseSearch();
}
});
After the changes from the solution @Andrew mentioned in the comments, I'm having issues at the first time of loading the component. From the second time the component is reloading and it's working.
Edit 3: I had to move the above code (this.navigationSubscription) from ngOnInit() to the constructor as ngOnInit() gets called only once.