Angular: How to update queryParams without changing route

后端 未结 8 524
日久生厌
日久生厌 2020-12-07 09:01

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :

$location.search(\'f\', \'filters[]\'); //         


        
相关标签:
8条回答
  • 2020-12-07 09:18

    First, we need to import the router module from angular router and declare its alias name

    import { Router } from '@angular/router'; ---> import
    class AbcComponent implements OnInit(){
    constructor(
        private router: Router ---> decalre alias name
      ) { }
    }
    

    1. You can change query params by using "router.navigate" function and pass the query parameters

    this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"} 
    });
    

    It will update query params in the current i.e activated route

    1. The below will redirect to abc page with _id, day and name as query params

      this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name: "dfd"} });

      It will update query params in the "abc" route along with three query paramters

    For fetching query params:-

        import { ActivatedRoute } from '@angular/router'; //import activated routed
    
        export class ABC implements OnInit {
    
        constructor(
            private route: ActivatedRoute //declare its alias name
          ) {}
    
        ngOnInit(){
           console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
        }
    
    0 讨论(0)
  • 2020-12-07 09:26

    Try

    this.router.navigate([], { 
      queryParams: {
        query: value
      }
    });
    

    will work for same route navigation other than single quotes.

    0 讨论(0)
提交回复
热议问题