【问题标题】:Angular 4 use typescript parse response dataAngular 4 使用 typescript 解析响应数据
【发布时间】:2017-11-08 14:31:15
【问题描述】:

我的响应数据如下:

{
  "content": [{
    "id": 1,
    "userName": "v7001",
    "status": 1,
    "userInfo": {
      "id": 1,
      "fullName": "Naruto Uzumaki",
      "firstName": "Naruto",
      "lastName": "Uzumaki",
      "address": "Konoha",
      "dob": 1509901200000
    }
  }, {
    "id": 2,
    "userName": "v7002",
    "status": 0,
    "userInfo": {
      "id": 2,
      "fullName": "Hinata Hyuga",
      "firstName": "Hinata",
      "lastName": "Hyuga",
      "address": "Konoha",
      "dob": 1509987600000
    }
  }],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}

和用户 Angular 4 来显示数据。我创建了 2 个界面:用户信息

export class UserInfo {
  id: number;
  fullName: string;
  firstName: string;
  lastName: string;
  address: string;
  dob: string
}

和用户

import {UserInfo} from './user-info'

export class User {
  id: number;
  userName: String;
  status: String;
  userInfo: UserInfo;
}

用户服务:

getUsers(): Promise<User[]> {
  return this.http.get(this.userUrl)
    .toPromise()
    .then(response => response.json().data as User[])
    .catch(this.handleError);
}

我检查了网络选项卡,API 成功获取数据。 在组件上:

user: User[];
selectedUser: User;
newUser: User;
data: any={};

constructor(private router: Router,
            private userService: UserService) {}

ngOnInit() {
  this.userService.getUsers().then(user => this.user = user); 
}

在 html 中:

 <tr role="row" class="odd" *ngFor="let lst of user.content">
   <td>{{lst.userInfo.fullName}}</td>
   <td>{{lst.userInfo.address}}</td>
</tr>

但是当应用程序运行时,控制台上显示错误消息:内容无效。 this.user 未定义。请给我建议。

【问题讨论】:

  • user 是组件中的一个数组,它没有 content 属性
  • 旁注:http 已被 Angular 团队弃用。请改用HttpClient

标签: javascript angular typescript


【解决方案1】:

如果您希望从getUsers 方法接收users 集合,那么请返回response.json().content,尽管response.json().data,然后User[] 为收集提供工具是有意义的User[]

getUsers(): Promise<User[]> {
  return this.http.get(this.userUrl)
    .toPromise()
    .then(response => response.json().content as User[])
    .catch(this.handleError);
}

消费

this.userService.getUsers().then(users => this.users = users);

HTML

<tr role="row" class="odd" *ngFor="let lst of users">
  <td>{{lst.userInfo.fullName}}</td>
  <td>{{lst.userInfo.address}}</td>
</tr>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2012-01-28
    相关资源
    最近更新 更多