例如,我在路上/cars?type=coupe
,我想用其他查询参数导航到同一个端点(但保留现有的查询参数).我正在尝试这样的事情
Click
保留初始查询参数(type = cars)但忽略添加的(model = renault).这是预期/正确的行为还是某种错误?看起来preserveQueryParams优先于queryParams?还有其他顺利解决方案吗?
在Angular 4+中,preserveQueryParams
已被弃用赞成queryParamsHandling
.选项是'merge'
或'preserve'
.
代码内示例(用于NavigationExtras
):
this.router.navigate(['somewhere'], { queryParamsHandling: "preserve" });
模板内例子:
它不幸地以这种方式工作:
const q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams;
您可以尝试添加这样的自定义指令:
@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); } } Click
更新:请参阅下面的DarkNeuron答案.