繁体   English   中英

错误 TS2345:类型为“字符串”的参数 | null' 不能分配给“数字”类型的参数

[英]error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'number'

使用我的 angular 应用程序编译和运行此代码时出现此错误

错误 TS2345:类型为“字符串”的参数 | null' 不能分配给“数字”类型的参数。 “null”类型不能分配给“number”类型。

在这一行: const id = this.activateRoute.snapshot.paramMap?.get('id');

完整代码:

 constructor(private shopService: ShopService, private activateRoute: ActivatedRoute) { } loadProduct(){ // tslint:disable-next-line: no-non-null-assertion const id = this.activateRoute.snapshot.paramMap?.get('id'); this.shopService.getProduct(id).subscribe(product => { this.product = product; }, error => { console.log(error); }); }

添加任何组件后,我得到了页面:cannot GET /

我想我很接近,并从相关方面找到了解决方案。 我改变了这一行:

const id = this.activateRoute.snapshot.paramMap?.get('id');

只是:

const id = +this.activateRoute.snapshot.paramMap.get('id')!;

错误消失了。 谢谢大家

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM