Search code examples
angularangular8routerlink

How to use a "complete Url" (url with params) for navigation in Angular


I have a search page with lots of filter options, these options are all passed to the url as params on the search page (so it is possible to share a search). when going to a detail page for one row in the search result, then I are parsing the complete Url for the search result to the detail page as a parameter (detail/1?returnUrl=%2Fsearch%2Fresults%3Fsw%3D%26n%3D%26ee%3D2%26a....), to make it possible to go back (on the detail page there are some tabs that is navigate to with routerlink, so I can't use any history back for navigating back to the search result).

The questions is, I have a complete URL on my detail page (eg. /search/result?a=1&b=people&c=8&d=all&p1=1), how do I navigate to that url?

If I put it in a routerlink="/search/result?a=1&b=people&c=8&d=all&p1=1" it isn't working.

Thanks very much in advance :)

UPDATE

I have tried the following, but it is not working:

 public goBack() {
    const returnUrl = this.activatedRoute.snapshot.queryParamMap.get('returnUrl');

    const array1 = returnUrl.split('?');
    const array = array1[1].split('&');

    let parameters = '';

    array.forEach(param => {
        const param1 = param.split('=');
        parameters += `${param1[0]}:'${param1[1]}',`;
    });

    this.router.navigate([array1[0]], { queryParams: {parameters} });

}

It writes the following link in the URL:

http://localhost:4200/search/results?parameters=sw:%27%27,n:%27%27,ee:%272%27,a:%27true%27,l:%27%27,c:%27%27,ad:%27%27,cr:%27%27,pn:%271%27,s:%271%27,sd:%271%27,


Solution

  • EDIT: Answer to your updated question

    the method navigate in Angulars router accepts Params as argument for the property queryParams - not a string.

    public goBack() {
        const returnUrl = this.activatedRoute.snapshot.queryParamMap.get('returnUrl');
    
        const array1 = returnUrl.split('?');
        const array = array1[1].split('&');
    
        let parameters = {};
    
        array.forEach(param => {
            const param1 = param.split('=');
            parameters[param1[0]] = param1[1];
        });
    
        this.router.navigate([array1[0]], { queryParams: parameters });
    
    }
    

    Below: Answer to question as it previous was formulated

    Query parameters should be passed in their own property.

    Check the examples at https://angular.io/api/router/RouterLink#description

    <a [routerLink]="['/search/result']" [queryParams]="{ 'a': 1, 'b': 'people', 'c': 8, 'd': 'all', 'p1': 1}">
      Products
    </a>