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

时间:2021-02-02 20:55:15

标签: angular typescript

我在使用 Angular 应用程序编译和运行此代码时遇到此错误

错误 TS2345:'string 类型的参数 | null' 不可分配给类型为 'number' 的参数。 类型 '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);
    });
  }

添加任何组件后,我得到了页面:无法获取 /

1 个答案:

答案 0 :(得分:0)

我想我很接近,并从相关人员那里找到了解决方案。 我改变了行:

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

只是:

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

并且错误消失了。 谢谢大家