如何解决:对象可能是'null'。在 angular 路由中?

how to solve : Object is possibly 'null'. in angular routing?

我正在做 angular 文档中的 angular 英雄教程。我遇到错误

Object is possibly 'null'.

getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
  .subscribe(hero => this.hero = hero);

}

英雄-detail.component.ts

link 整个代码 hero-detail component

我在config.json中看到了太多的答案,以至于把它弄错了。 我需要帮助解决这个问题,但不能压制它。

提前致谢。

这是由于杂散的加号加上项目 this.route.snapshot.paramMap.get('id') 根据 Typescript 类型系统实际上可能为空,因此它不是 +.[=17 的合法操作数=]

我在 this playground

使用此代码重新创建了相同的错误
const thing:string|null;

function getHero() : void {
const id = +thing;
}

注意那一行...

const id = +thing;

如果根据下面 Elisio 的评论使用 +,那么您需要做一些事情来保护命令,这样当 id 为 null 时 getHero 根本不会 运行,或者在 运行 之前为 id 提供可靠的替代值。只要有可能为空,那么

Typescript 无法保证操作一定会完成。这很好,因为它会强制您进行检查并增加安全性。

分两步完成

getHero(): void {
  const param=this.route.snapshot.paramMap.get('id');
  const id = param?+param:0;
  this.heroService.getHero(id)
    .subscribe(hero => this.hero = hero);
}