Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

Getting error while reading a property after calling a rest service from Angular

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`);


          }
        
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to add the message inside subscribe method:

getHero(): void {
  this.id = +this.route.snapshot.paramMap.get('id');
  this.heroService.getHero(this.id).subscribe(hero => {
    this.hero = <Hero> hero;
    this.messageService.add(`Hero with Id : ${this.hero.id} is selected`);
  }); 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...