In angular 2 how to preserve query params and add additional query params to route

后端 未结 4 785
一生所求
一生所求 2020-12-29 22:00

For example I am on route /cars?type=coupe and I want to navigate to the same endpoint with additional query params (but keeping existing one). I am trying some

相关标签:
4条回答
  • 2020-12-29 22:29

    It just works this way unfortunately:

    const q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams;

    You could try to add custom directive like this:

    @Directive({selector: 'a[routerLink][merge]'})
    export class RouterLinkDirective implements OnInit
    {
    
        @Input()
        queryParams: {[k: string]: any};
    
        @Input()
        preserveQueryParams: boolean;
    
    
        constructor(private link:RouterLinkWithHref, private route: ActivatedRoute )
        {
        }
    
        public ngOnInit():void
        {
            this.link.queryParams = Object.assign(Object.assign({}, this.route.snapshot.queryParams), this.link.queryParams);
            console.debug(this.link.queryParams);
        }
    }
    
    
    <a [routerLink]="['/cars']" merge [queryParams]="{model: 'renault'}">Click</a>
    

    Update: See DarkNeuron answer below.

    0 讨论(0)
  • 2020-12-29 22:30

    This can be handled using relativeTo and queryParamsHandling properties.

    Try like this:

    constructor(private _route: ActivatedRoute, private _router: Router)
    
    
    this._router.navigate(
        [],
        {
          relativeTo: this._route,
          queryParams: { model: 'renault' },
          queryParamsHandling: 'merge'
     });
    
    0 讨论(0)
  • 2020-12-29 22:45

    In Angular 4+, preserveQueryParams have been deprecated in favor of queryParamsHandling. The options are either 'merge' or 'preserve'.

    In-code example (used in NavigationExtras):

    this.router.navigate(['somewhere'], { queryParamsHandling: "preserve" });
    

    In-template example:

    <a [routerLink]="['somewhere']" queryParamsHandling="merge">
    
    0 讨论(0)
  • 2020-12-29 22:48

    There is an open issue and also already a pull request to make preserveQueryParams a router setting instead of a per navigation setting

    • https://github.com/angular/angular/issues/12664
    • https://github.com/angular/angular/pull/12979
    • https://github.com/angular/angular/issues/13806
    0 讨论(0)
提交回复
热议问题