无法从 ActivatedRoute 获取查询参数
Can't get query parameters from ActivatedRoute
我在路由模块中定义了这样一条路由:
{ path: 'warning/:type', component: WarningPageComponent }
当应用程序想要导航到警告页面时,将进行此调用:
const navigationExtras: NavigationExtras = {
queryParamsHandling: 'preserve',
queryParams: { errorCode: '12345'}
};
return this.router.navigate(['/warning/default'],navigationExtras);
在WarningPageComponent
中参数是这样读取的ngOnInit()
:
const params = this.route.snapshot.paramMap;
console.log('ERR warning page' + JSON.stringify(params));
const errorCode = params.get('errorCode') ?? undefined;
const type = params.get('type') ?? undefined;
现在的问题是 paramMap
中只有 type
,errorCode
中没有。这里有什么问题?我也试过 queryParamsHandling: 'preserve'
Angular 8.2.14
我在以下方面找不到解决方案:
如果要访问 queryParams,则必须在快照对象上使用 queryParamMap。
const queryParams = this.route.snapshot.queryParamMap;
const errorCode = queryParams.get('errorCode') ?? undefined;
像这样获取构造函数中的参数
import { ActivatedRoute } from '@angular/router';
export class DashboardComponent implements OnInit, AfterViewChecked, OnDestroy {
queryParams: any;
constructor(private activatedRoute: ActivatedRoute) {
this.queryParams = Utils.paramsToLower(this.activatedRoute.snapshot.queryParams);
}
}
我在路由模块中定义了这样一条路由:
{ path: 'warning/:type', component: WarningPageComponent }
当应用程序想要导航到警告页面时,将进行此调用:
const navigationExtras: NavigationExtras = {
queryParamsHandling: 'preserve',
queryParams: { errorCode: '12345'}
};
return this.router.navigate(['/warning/default'],navigationExtras);
在WarningPageComponent
中参数是这样读取的ngOnInit()
:
const params = this.route.snapshot.paramMap;
console.log('ERR warning page' + JSON.stringify(params));
const errorCode = params.get('errorCode') ?? undefined;
const type = params.get('type') ?? undefined;
现在的问题是 paramMap
中只有 type
,errorCode
中没有。这里有什么问题?我也试过 queryParamsHandling: 'preserve'
Angular 8.2.14
我在以下方面找不到解决方案:
如果要访问 queryParams,则必须在快照对象上使用 queryParamMap。
const queryParams = this.route.snapshot.queryParamMap;
const errorCode = queryParams.get('errorCode') ?? undefined;
像这样获取构造函数中的参数
import { ActivatedRoute } from '@angular/router';
export class DashboardComponent implements OnInit, AfterViewChecked, OnDestroy {
queryParams: any;
constructor(private activatedRoute: ActivatedRoute) {
this.queryParams = Utils.paramsToLower(this.activatedRoute.snapshot.queryParams);
}
}