angular - 无法读取未定义的属性成功
问题描述
ERROR TypeError: Cannot read property 'success' of undefined
at Object.eval [as updateRenderer] HomeComponent.html:1
console.log(userDetail); 得到这个https://i.imgur.com/HNZ5PRg.png
该应用程序编译成功,并且在 Home Component HTML 中它正确打印了 first_name 但控制台仍然显示我上面提到的错误。
HTML 文件
<div *ngIf="isLoggedIn">
{{userDetail.success.first_name}}
</div>
打字稿文件
ngOnInit() {
this.chk.checkLogin();
this.chk.isUserLoggedIn.subscribe( (val) => {
if(val) {
this.isLoggedIn=val;
}
})
//get user profile
this.chk.getUserProfile().subscribe((res: any)=> {
this.userDetail = res;
console.log(this.userDetail);
});
身份验证服务文件
//Get User Profile
getUserProfile() {
return this.http.post(this.userProfileApi, null);
}
解决方案
当您从异步请求中获取配置文件时,将抛出错误,因为数据不可用,您可以使用safe navigation operator
(?) 处理它,如下所示
<h2 *ngIf="isLoggedIn">
{{userDetail?.success?.first_name}}
</h2>
推荐阅读
- html - 如何在 Firefox 中禁用/删除“不允许 localhost:8082 再次提示您”功能
- java - 登录失败或关闭登录浏览器时的应用通知 - Keycloak.loginDesktop()
- flutter - 是否可以从回车分隔的字符串构建列表?
- validation - L8 - 从另一个 FormRequest 发出 FormRequest 失败
- javascript - JSON返回主函数的问题
- authentication - 如何从页面中分离赛普拉斯测试运行器?
- vue.js - Vue测试库,子组件接收props
- sas - 从字符串 SAS 中删除值
- angularjs - AngularJS $location.search 不适用于 URL 中间的查询参数
- r - 按 chunk_size 写入多个 parquet 文件