Search code examples
angulartypescriptangular-routing

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


As I am doing angular heroes tutorial from angular documentation. I am getting an error

Object is possibly 'null'.

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

}

in hero-detail.component.ts

link for the whole code hero-detail component

I have seen so many answers that to make it false in config.json. I need help with how to solve this, but not suppressing it.

Thanks in Advance.


Solution

  • you can do it in two steps

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