我想将用户数据传递到其个人资料中。我从 api 获得了完整的数据,我可以获取它并将其显示在用户页面上。但是,当我想在用户个人资料页面上显示来自用户的数据时,出现此错误:
TypeError: Cannot read property 'username' of null
路由有效。但不知何故,我无法访问我想存储在 information
中的用户信息。我认为这一行应该存储用户的数据:
this.userService.getUserDetails(id).subscribe(result => {
this.information = result;
});
我该如何解决? 这是我的代码:
用户服务
// get a list of users
getList(): Observable<any> {
return this.http.get(`${this.url}/users`);
}
// get a user's profile
getUserDetails(id): Observable<any> {
return this.http.get(`${this.url}/users/?i=${id}`); // why add ?i
}
用户.page.ts
getAllFriends() {
this.friendsList = this.userService.getList()
.pipe(map(response => response.results));
}
个人资料.page.ts
information = null;
...
ngOnInit() {
// Get the ID that was passed with the URL
let id = this.activatedRoute.snapshot.paramMap.get('id');
// Get the information from the API
this.userService.getUserDetails(id).subscribe(result => {
this.information = result;
});
}
profile.page.html
<ion-label text-wrap>
<h6 class="subinfo">{{information.username}}, 22, 3589</h6>
</ion-label>
最佳答案
您的组件以 information = null;
开头,所以在 {{ information.username }}
中出现此错误是正常的。
一个快速的解决方案是:
{{ information?.username }}
关于javascript - 尝试访问 ID 数据时无法读取 null 的属性 'username',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58738652/