0
votes

I have a search page, where the user can perform a search and see a result.

Initially, my issue was to update the router URL without navigating, but I solved that by using "Location".

My ngOnInit - my search page can be navigated to by another page, so I listen for queryParams to perform the search if any happens:

ngOnInit() {    
    this.queryParamsSubscription = this.activatedRoute.queryParams.subscribe(queryParams => {
      this.searchText = queryParams[TD_QUERY_PARAMS.text];
      if (this.searchText) {
        this.search();
      }
    });
  }

my search method:

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 implementation makes sure that I update the URL when the user searches within the search page, which was the first part of my solution.

However, I also want to add any search to the browser history, ie:

  • I start by launching my application on 'localhost:4200/landing'.

  • On this page, I have a search bar, that when triggered will navigate to my search page.

  • From the landing page, I search for '1'. The router then navigates to: 'localhost:4200/search?text=1'

  • Then on the search page, I search for '2'. the search is performed, and the URL is updated to: 'localhost:4200/search?text=2'

  • Finally I search for '3': ''localhost:4200/search?text=3'.

When I then press the browsers 'Back' button, I would expect to be navigated to ''localhost:4200/search?text=2'.

However, none of the searches I made within the page has been added to history, so I will be navigated to whatever page I was accessing before the search page. In my case, 'localhost:4200/landing'.

How can I add each of these searches to the browsers history?

2

2 Answers

1
votes

I believe that one of these is what yo need:

  1. this.router.navigate(['/yourRouteGoesHere'], { replaceUrl: true });

  2. The other options that you have is to use: SkipLocationChange this.router.navigateByUrl(['yourFullPath'], { skipLocationChange: true });

  3. use this.router.replaceUrl('path').

That way you can navigate, without adding this route to history.

0
votes

This was a case of way overthinking the issue I was facing.

By just using router.navigate(['/search'], { queryParams: queryPrams })

I got the result I desired. The URL was changed, a point was added to browser history.

What I failed to realize, was that router.navigate, will not reload the entire page, when only the queryParams are changed.

Hope this helps anyone struggling with the same issue.