我有如下响应数据:
{
"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 个接口(interface):用户信息
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 未定义。请给我建议。
最佳答案
如果您希望从 getUsers
方法接收 users
集合,那么尽管 返回
,然后是 response.json().content
>response.json().dataUser[]
为收集成为 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>
关于javascript - Angular 4 使用 typescript 解析响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182319/