javascript - 尝试访问 ID 数据时无法读取 null 的属性 'username'

标签 javascript angular typescript ionic-framework

我想将用户数据传递到其个人资料中。我从 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}},&nbsp;22,&nbsp;3589</h6>
</ion-label>

最佳答案

您的组件以 information = null; 开头,所以在 {{ information.username }} 中出现此错误是正常的。

一个快速的解决方案是:

{{ information?.username }}

关于javascript - 尝试访问 ID 数据时无法读取 null 的属性 'username',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58738652/

相关文章:

Angular i18 国际化,以编程方式更改语言

html - 在pdfmake中如何从字符串打印html数据

TypeScript: "catch"并在条件中显式处理未解析的泛型?

javascript - javascript 代码应该始终加载在 html 文档的头部吗?

javascript - 当用户单击按钮(在光标位置)时,将一串文本添加到输入字段中

javascript - 我的日期选择器始终在当月打开

Angular2 Ng2文件上传CORS问题

node.js - Node Docker 构建和生产容器最佳实践

javascript - Div 未显示

javascript - 虽然可见,但如何使此对话框阻止访问其余页面内容?