Angular TypeScript将嵌套模型作为数组访问

时间:2019-06-12 16:19:07

标签: arrays angular nested typescript2.0

试图访问父接口的子成员(是一个数组)。 但是得到undefined

export class Address {
    id: number;
    city: string;
    state: string;
}

import { Address } from './address';
export class User {
    id: number;
    name: string;
    alladdresses: Address[];
}

在我的组件中-声明是

  users: User[] = [];
  address: Address[] = [];

我的http.get

    selectUser(user: User) {
    let url = "http://localhost:8080/users/" + user.id
    this.http.get<User>(url).subscribe(

      res => {
        //console.log(res);
        this.selectedUser = res;
        console.log('selected user is:', this.selectedUser);

      },
      error => {
        console.log('error while getting user for ', user.id);
      },
      () => {
        console.log('complete');
      }
    );
  }

并且用户的json响应是 enter image description here

我在页面上显示的是所选用户,页面上的某些操作调用了另一个函数来访问地址-数组

createAddress() {
    let newAddress: Address = {
      id: null,
      city: "new city",
      state: "new state"
    }
    console.log(this.selectedUser)
    let address: Address[] = this.selectedUser.alladdresses
    //address.push(newAddress);
    console.log(address);
  }

但是数组是不确定的,不是哪里出错了。 enter image description here

1 个答案:

答案 0 :(得分:1)

您的http.get方法返回的数据与期望的数据之间似乎不匹配。您的api返回名为addresses的地址,而您期望返回alladdresses