TypeError:无法读取未定义的属性“ email”(角度)

时间:2020-09-09 09:08:38

标签: angular undefined

我有一台服务器,可以向我返回一个对象,并且在页面上一切正常,但是在控制台中,我有这个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);
  }

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

尝试重构您的代码,并将Angular的observable用作:

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

getById(id : string) : Observable

在您的组件类中,方法应类似于:

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

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

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

编辑:{{candidate?.email}} 加?在求职者之后,这将帮助您清空求职者的值

答案 1 :(得分:0)

将变量candidate初始化为一个空对象。

candidate: ICandidatesInfo = {};

答案 2 :(得分:0)

您可以使用Observable,而不是使用async / await。

candidate$: Observable<ICandidatesInfo>;

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

public getCandidate() {
    this.candidate$ = this.candidateInfoService
      .getById(this.route.snapshot.params['id']); // No need to call subscribe here
}

在您的html中:

<div *ngIf="candidate$ | async; let candidate">
    <p>{{candidate.email}}</p>
</div>

如果您介意制作一个额外的<div>标签,可以将其更改为:

<ng-container *ngIf="candidate$ | async; let candidate">
    ...
</ng-container>