我有如下响应数据:
{
"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
}和用户角度4来显示数据。我创建了两个界面:用户信息
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是未定义的。请给我建议。
发布于 2017-11-08 14:48:39
如果您希望从getUsers方法接收getUsers集合,那么尽管有response.json().data,仍然要返回response.json().content,然后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);<tr role="row" class="odd" *ngFor="let lst of users">
<td>{{lst.userInfo.fullName}}</td>
<td>{{lst.userInfo.address}}</td>
</tr>https://stackoverflow.com/questions/47182319
复制相似问题