Angular2 router keep query string

前端 未结 9 1704
栀梦
栀梦 2020-11-29 01:52

I wrote an Angular2 (v2.0.1) application that makes use of the router. The website is loaded with several query string parameters, so the full URL initially looks like this:

相关标签:
9条回答
  • 2020-11-29 02:20

    You may want to search https://github.com/angular/angular/issues for a feature request similar to this. If none exists, submit a feature request.

    In the mean time: I believe you will need to create a component, on the path: '', with the sole purpose of then redirecting to '/comp1' while preserving the QueryString params.

    0 讨论(0)
  • 2020-11-29 02:22

    If you are navigating using HTML template, you can also use preserveQueryParams="true"

    Notice that preserveQueryParams is without a square bracket.

    Eg:

    <a [routerLink]="['/navigate-to']" preserveQueryParams="true">

    0 讨论(0)
  • 2020-11-29 02:28

    After having had a go at most answers, I found that

    • Günter Zöchbauer's answer doesn't work for me at all
    • Christopher's suggestion of removing the leading / didn't do it either
    • AArias' answer did work but lead to the adding of two urls in the history:
      1. https://my.application.com/comp1?param=val <= ( ಠ 益ಠ )
      2. https://my.application.com/comp1;param=val

    So here's yet another approach, that eventually behaved as per my expectations:

    import { ActivatedRoute, Router } from '@angular/router';
    
    class Component {
        constructor(private route: ActivatedRoute, private router: Router) {}
    
        someMethod() {
            router.navigate(['/comp1', this.route.snapshot.params]);
        }
    }
    
    0 讨论(0)
提交回复
热议问题