angular - 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);
}
非常感谢您的帮助!
解决方案
尝试重构您的代码并使用 Angular 的 observable 作为:
在您的服务中,将您的 getById 方法设置为:
getById(id : string) : Observable
在你的组件类方法应该是这样的:
getCandidate() {
this.candidateInfoService
.getById(this.route.snapshot.params['id'])
.subscribe(candidate => this.candidate = candidate);
}
现在来回答您的问题,错误类型错误:无法读取未定义的属性“电子邮件”
这表明您的候选人未定义,因此无法收到电子邮件。尝试重构您的代码并检查它是否有效!
编辑:{{candidate?.email}} 添加?在候选人之后,这将帮助您检查候选人的价值
推荐阅读
- reactjs - 如何将孩子传递给 nextjs 类?
- python-3.x - 有没有办法自定义 pandas.DataFrame.head()?
- docker - 当节点死亡时,Docker Swarm 不调度容器
- javascript - 如何将对象替换为具有特定唯一字段值的数组?
- react-native - 在 React Native 中渲染 JSX
- r - 在 R 中无法访问返回函数
- javascript - JavaScript 中 switch-case 语句中的变量声明
- javascript - 为什么我的 CSS 没有被捆绑到应用程序中?
- xamarin.forms - INavigationService 的包装器或代理
- python - 如何在不将其加载到 RAM 的情况下添加到 Numpy 数组?