Search code examples
angularangular9angular-router

Query parameters and url are not getting updated correctly


constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,

  ) {}

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(params => {  //subscribe to param change
      console.log('params', params)

  }

  updateQueryParams(queryParam:any): void {

    this.router.navigate([],
      {
        queryParams: queryParams,
        relativeTo: this.activatedRoute,
        queryParamsHandling: 'merge',
      })
  }

If initially my url is just http://localhost:8080/emp-searchand I send this object to query Param,

{name:'test', email: 'test'}

the route updates correctly to http://localhost:8080/emp-search?name=test&email=test and param change are caught in my ngOnInit()

After that if I call my updateQueryParams() method again and send this object as queryParams {name:'test'}. The url doesn't update and stays http://localhost:8080/emp-search?name=test&email=test and no param changes are caught in the ngOnInit()

However, if I instead send this object

{name:'test', email: 'test', id: '1'}

the url updates correctly to this http://localhost:8080/search?name=test&email=test$id=1


Solution

  • remove "queryParamsHandling: 'merge'" from navigate options In your "updateQueryParams" function and it should work