One of the features on my search page allows users to perform searches and view results.
Initially, I faced a challenge in updating the router URL without navigating, but I managed to overcome this by utilizing the "Location" feature.
In my ngOnInit method - as my search page can be accessed from another page, I have set up a listener for query parameters so that a search can be triggered if any are present:
ngOnInit() {
this.queryParamsSubscription = this.activatedRoute.queryParams.subscribe(queryParams => {
this.searchText = queryParams[TD_QUERY_PARAMS.text];
if (this.searchText) {
this.search();
}
});
}
The search method is defined as follows:
search() {
const queryParams: Params = { text: this.searchText };
const desiredUrl = this.router.createUrlTree([], {
queryParams: queryParams,
relativeTo: this.activatedRoute,
skipLocationChange: true
});
this.location.replaceState(desiredUrl.toString());
}
This approach ensures that the URL is updated when a user performs a search within the search page, covering the first part of my solution.
However, I also aim to include each search in the browser history, illustrated by the following steps:
I initially launch the application at 'localhost:4200/landing'.
From the landing page, I use the search bar to navigate to the search page.
Upon reaching the search page, I search for '1', resulting in navigation to: 'localhost:4200/search?text=1'
Subsequently, I conduct a search for '2' on the search page, which updates the URL to: 'localhost:4200/search?text=2'
Lastly, I perform a search for '3', leading to the URL: ''localhost:4200/search?text=3'.
When attempting to go back using the browser's 'Back' button, the expected behavior would be to return to 'localhost:4200/search?text=2'. Unfortunately, none of the searches made on the page are recorded in the history. As a result, the navigation reverts to the previous page, 'localhost:4200/landing'.
Any suggestions on how I can add these searches to the browser's history?