无法从激活路由获取查询参数



我在路由模块中定义了这样的路由:

{ 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'

角度8.2.14

我在中找不到解决方案

  • 角度擦除所有查询参数
  • 父组件从ActivatedRoute获取空参数
  • 如何从Angular ActivatedRoute获取参数

如果要访问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);
}
}

最新更新