我正在尝试为我的应用程序的某些URL添加查询参数。我正在使用快照方法,并且我有一个将查询参数添加到 URL 的函数。一切正常,除了当我尝试将查询参数添加到我的主 URL 时,我的 URL 被
{ path: '**', redirectTo: 'not-found'}
它被重定向到 NotFoundComponent。
我的主页组件的路径定义如下:
{ path: ':language', component: HomeComponent}
该函数的定义如下:
this.router.navigate(['en'], {
queryParams: {'param1': this.value1, 'param2': this.value2}
});
我知道该函数有效,因为当我尝试为其他组件添加查询参数时,如下所示:
this.router.navigate(['en/other-component'], {
queryParams: {'param1': this.value1, 'param2': this.value2}
});
没有问题,我被重定向到想要的页面,查询参数被传递给 URL。
如果第一段不以/开头,则为相对路由。 router.navigate 需要一个相对 To 参数进行相对导航
this.router.navigate(['en'], {
queryParams: {'param1': this.value1, 'param2': this.value2},relativeTo: this.route
});
例:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
templateUrl: ''
})
export class Component {
constructor(
private route: ActivatedRoute,
private router: Router) {}
goToEdit(person:Person) {
this.router.navigate([ en ], { relativeTo: this.route });
}
}