I am new to Angular and working on a mock application. I am trying to call a rest service and then reading a property from the response object in Angular but getting an error. Below is the code that I am trying and the error I am getting.
Error
core.js:5967 ERROR TypeError: Cannot read property 'id' of undefined
at HeroDetailComponent.getHero (hero-detail.component.ts:33)
I am stuck at this step. That would be really appreciated if I can get some help here.
export class HeroService {
heroServiceUrl = 'http://localhost:8081';
getHero(id:number): Observable<Hero>{
(this.heroServiceUrl+`/getHero/${id}`).pipe(catchError(this.handleError<Hero>('getHero',)));
}
handleError<T>(operation = 'operation', result?: T){
return (error: any): Observable<T> => {
return of(result as T);
}
}
constructor(private httpClient: HttpClient) { }
}
export class HeroDetailComponent implements OnInit {
hero: Hero;
constructor(private route: ActivatedRoute,
private heroService: HeroService,
private messageService: MessageService,
private location: Location) { }
ngOnInit(): void {
this.getHero();
}
id: number;
getHero(): void{
this.id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(this.id).subscribe(hero => this.hero = <Hero> hero);
// Getting error at this line.
this.messageService.add(`Hero with Id : ${this.hero.id} is selected`);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…