Angular erasing all query parameters

后端 未结 4 1915
失恋的感觉
失恋的感觉 2021-01-07 04:00

Related to but not a duplicate of: How to keep query string parameters in URL when accessing a route of an Angular 2 app?

I have a very basic Angular app, and when I

相关标签:
4条回答
  • 2021-01-07 04:21

    The issue you are having is because you are calling this.router.navigate(['/calculator'], navigationExtras); inside your app component constructor or OnInit. Remember that queryParamMap is an observable, and so when you call navigate, the call will happen before your subscriber gets called. To fix your problem, just remove the navigate call. If you want your app component to autoredirect to calculator, the simplest safe method is to just change your paths to include:

    routes: Routes = [ {path: '', redirectTo: 'calculator', pathMatch: 'full'}, ... ]

    There is a plunker that should illustrate this. To get routing in plunker working I used HashLocation strategy though, so make sure you use /#/... when playing.

    0 讨论(0)
  • 2021-01-07 04:35

    This should work.

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute
        ) { }
    
    resetUrlQueryParams(){
      this.router.navigate([], 
          {
            relativeTo: this.activatedRoute,
            queryParams: {}
          });
    }

    0 讨论(0)
  • 2021-01-07 04:37

    if you want to retrieve query paramaters, then it is done using queryParam/queryParamMap..

    this.route.queryParamMap.subscribe(params => {
       console.log(params);
    });
    

    You may need to preserve the query parameters, or merge them as stated here.

    https://angular.io/api/router/NavigationExtras

    v4

    preserveQueryParams: true
    

    v5

    queryParamsHandling: 'preserve'
    
    0 讨论(0)
  • 2021-01-07 04:39

    You need to assign your query params to the queryParams Object.

    Try:

    this.router.navigate(['/calculator'], {queryParams: {a: 1}});
    

    or add this to your navigation extras:

    let navigationExtras: NavigationExtras = {
        queryParamsHandling: 'preserve',
        preserveFragment: true,
        queryParams: {a:1}
    };
    
    0 讨论(0)
提交回复
热议问题