在 Angular 中使用 httpClient 获取嵌套对象

Get nested object with httpClient in Angular

我试图通过获取请求让嵌套对象显示在模板中。问题是它显示了我的对象的主要属性,尽管是嵌套对象。

export class User {
 userId: number;
 userName: string;
 password: string;
 firstName: string;
 lastName: string;
 role: number;
 inforamation: Information;
}

这是我的模型,可以显示用户属性但不能显示信息。

getAllUsers(){
    const header = new HttpHeaders({
      'Content-Type':  'application/json'
    });
    return this.usersapiservice.getData(this.REST_API_SERVER, {headers : header});
  }



ngOnInit(){
this.getAllUsers().subscribe((data: User[]) => {
      this.users = data;
    });
}

在我的html

{{users.firstname}} // work

{{users.information.adress}} // Does not work`

我看到了几个问题。在 User class 中,您将其中一个属性拼错为 inforamation,但在模板中,属性 被正确拼写为 information.

如果你有一个User的数组要渲染,你可以使用Angular的*ngFor来遍历它们,如下所示:

<div *ngFor="let user of users">
  {{user.firstName}}
  {{user.information.address}}
</div>