相关但不重复:How to keep query string parameters in URL when accessing a route of an Angular 2 app?
我有一个非常基本的Angular应用程序,当我在代码命中 app.component
构造函数之前添加一个查询参数时,它会显示在其他任何地方 .
Note :在初始加载(以及后续重新加载)时,查询参数似乎被剥离
示例:导航到 localhost:8081/calculator?a=1
更改为 localhost:8081/calculator
我在Angular 4.3.1,4.4.6和5.0.4中尝试了这个,结果相同 .
这是我的路线配置:
const appRoutes: Routes = [
{
path: 'calculator',
component: CalculatorComponent
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
这是主要的app组件的构造函数:
public constructor(private router: Router, private route: ActivatedRoute) {
console.log('entered app constructor');
this.route.queryParamMap.subscribe(params => {
console.log('app', params);
});
}
这是计算器组件的构造函数:
constructor(private router: Router, private route: ActivatedRoute) {
console.log('entered calc constructor');
this.route.queryParamMap.subscribe(params => {
console.log('calc', params);
});
}
这是我在chrome中看到的日志:
为什么我的查询参数被删除了?
UPDATE 我确实在app组件中配置了导航,如下所示:
let navigationExtras: NavigationExtras = {
queryParamsHandling: 'preserve',
preserveFragment: true
};
this.router.navigate(['/calculator'], navigationExtras);
请注意,查询参数在到达之前已经消失了......
4 回答
您遇到的问题是因为您在应用程序组件构造函数或OnInit中调用
this.router.navigate(['/calculator'], navigationExtras);
. 请记住,queryParamMap是一个可观察的,因此当您调用navigate时,调用将在您的订阅者被调用之前发生 . 要解决您的问题,只需 remove the navigate call . 如果您希望您的应用程序组件自动重定向到计算器,最简单的安全方法是只更改您的路径包括:routes: Routes = [ {path: '', redirectTo: 'calculator', pathMatch: 'full'}, ... ]
有一个plunker应该说明这一点 . 为了在plunker工作中获取路由,我使用了HashLocation策略,因此请确保在播放时使用
/#/...
.如果要检索查询参数,则使用queryParam / queryParamMap完成 .
您可能需要保留查询参数,或者按照此处所述合并它们 .
https://angular.io/api/router/NavigationExtras
V4
V5
您需要将查询参数分配给queryParams对象 .
尝试:
或将此添加到您的导航附加功能:
这应该工作 .