【问题标题】:how to solve : Object is possibly 'null'. in angular routing?如何解决:对象可能是“空”。在角度路由?
【发布时间】:2021-04-07 16:56:30
【问题描述】:

当我在 Angular 文档中做 Angular Heroes 教程时。我收到一个错误

对象可能是“空”。

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

}

hero-detail.component.ts

完整代码链接hero-detail component

我在 config.json 中看到了很多答案,以至于将其设为假。 我需要有关如何解决此问题的帮助,但不要压制它。

提前致谢。

【问题讨论】:

    标签: angular typescript angular-routing


    【解决方案1】:

    你可以分两步完成

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

    【讨论】:

    • 那么我们是否应该在使用路由时访问另一个变量?
    【解决方案2】:

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

    我在this playground 使用此代码重新创建了相同的错误

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

    注意上面写着...的那一行

    const id = +thing;
    

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

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

    【讨论】:

    • 这种情况下你可以const id=thing?+thing:0
    • 我对错误的解释是,加号已经潜入其中并且不是故意的,而是创建了一个编译器错误,OP 无法在一个原本只是一个声明的语句中解释简单的赋值... const id = this.route.snapshot.paramMap.get('id')
    • 我不太确定,但我认为错误在于您不能“操作”一个可以为空的变量,但您可以将一个变量与另一个变量相等(或可以是)空。 “+”是一种将您知道是数字的字符串转换为数字的简短方法:+"2"is 2 就像说 Number("2")
    • 很有趣,谢谢。我没用过,但现在我知道了。
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 2021-09-27
    • 2021-10-21
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2021-01-24
    • 2019-11-10
    相关资源
    最近更新 更多