Search code examples
angulartypescriptangular-routing

Angular router is not emitting query params when we only change the order


I have a big application that uses a backend and we can order by using query params :

my-resource?field1=asc&field2=desc will gives order by field1 asc, field2 desc

but sometimes, i will invert these params :

my-resource?field2=desc&field1=asc will gives order by field2 desc, field1 asc

so in my code, i have a component that emit the new query params using an url tree and navigateByUrl :

url = 'my-resource';

navigateTo() {
     this.navigateByUrl(this.getUrlTree())
}

getUrlTree() {
    this.router.createUrlTree([this.url], { queryParams: this.orderedQueryParams });
}

And i have antother component that listens to the queryParams change :

constructor(private _route: ActivatedRoute) {}

ngOnInit() {
     this._route.queryParams
      .takeUntil(this._destroyed$)
      .do(async params => {
        console.log('params', params);
        this.doRequestToResource(params);
      }).subscribe();
}

The problem is that when I navigate from ?field1=asc&field2=desc to ?field2=desc&field1=asc I did not receive the event in the queryParams observable, when I go from field1=asc&field2=desc to field1=desc&field2=asc it works but if we try to invert the order of the parameters, it doesn't emit any observable value.


Solution

  • Since order is important to you maybe another approach is needed for the query params.

    One idea would be to use just one query param like this

    example.is/?q=field1;desc,field2;asc
    

    And then in your code you will just have to do some splitting to get the params.

    This is not tested code, just to get the idea across

    const splitted = params.split(',') // results = ['field1;desc', 'field2;asc']
    const more_split = splitted.map(_ => _.split(';'))