首页 > 解决方案 > TypeError:无法读取未定义的属性“电子邮件”(Angular)

问题描述

我有一个服务器,它返回一个对象,在页面上一切正常,但在控制台中我有这个TypeError。我知道这是因为ngOnInit有 Observable\Promise\Async 方法,而不是等待响应,但为什么我的async await不起作用?

这是我的代码:

candidate: ICandidatesInfo;

ngOnInit(): void {
    this.getCandidate();
}

async getCandidate() {
    await this.candidateInfoService
      .getById(this.route.snapshot.params['id'])
      .toPromise().then((candidate) => {
        this.candidate = candidate;
      });
}

.html我使用{{candidate.email}}中,我可以在页面上看到结果,但在控制台中仍然有错误ERROR TypeError: Cannot read property 'email' of undefined

这是我的另一个版本Observable

在役:

getById(id: string): Observable<ICandidatesInfo> {
  return this.http.get<ICandidatesInfo>(`${this.url}/${id}`);
}

功能:

getCandidate() {
     this.candidateInfoService
      .getById(this.route.snapshot.params['id'])
      .subscribe(candidate => this.candidate = candidate);
  }

非常感谢您的帮助!

标签: angularundefined

解决方案


尝试重构您的代码并使用 Angular 的 observable 作为:

在您的服务中,将您的 getById 方法设置为:

getById(id : string) : Observable

在你的组件类方法应该是这样的:

getCandidate() {
     this.candidateInfoService
      .getById(this.route.snapshot.params['id'])
      .subscribe(candidate => this.candidate = candidate);
}

现在来回答您的问题,错误类型错误:无法读取未定义的属性“电子邮件”

这表明您的候选人未定义,因此无法收到电子邮件。尝试重构您的代码并检查它是否有效!

编辑:{{candidate?.email}} 添加?在候选人之后,这将帮助您检查候选人的价值


推荐阅读