这是我的json文件的例子
{
"id": 5,
"url": "http://localhost:8000/api/v1/users/5/",
"username": "Najmuddin",
"email": "",
"groups": [
{
"id": 1,
"url": "http://localhost:8000/api/v1/groups/1/",
"name": "KETUA UNIT SEKSYEN",
"permissions": [
"Can add level",
"Can change level",
"Can delete level"
]
}
]
},
这是我的代码
public getUser(){
this.jobService.getUsers().subscribe(
user => {
for (let i = 0; i < user.length; i++) {
this.user = user;
let username = user[i].username; --> i can get id,url,username,...
let group = user[i].groups; --> i only get the [object] but i want
to get the id, url, and name instead
}
},
);
}
我只能获取并显示User的对象,而不能获取组id,url和name and permission
[object]`。这是我遗失的东西吗?
答案 0 :(得分:0)
试试这段代码
gcc -Wall ...
如果console.log(用户名)显示未定义,则输入console.log(this.username)。并删除?如果您确定组数组不为空
for * ngFor你可以这样做
userlist: any;
public getUser(){
this.jobService.getUsers().subscribe(
user => {
this.userlist=user;
for (let i = 0; i < user.length; i++) {
let username = this.userlist[i].username;
let group = this.userlist[i].groups;
let id = this.userlist[i].groups[0]?.id;
let url = this.userlist[i].groups[0]?.url;
console.log("********* start *******");
console.log(username);
console.log(group);
console.log(id);
console.log(url);
console.log("********* end *******");
}
},
);
}
答案 1 :(得分:0)
您可能想要嵌套的ngFor
<div *ngFor="let user of userlist">
<p>{{user.username}}<p>
<p *ngFor="let group of user.groups">{{group.id}} ...<p>
</div>
这样一来,如果没有填充user.groups,你就不会有错误。
答案 2 :(得分:0)
无需订阅即可使用Observable
public let users$: Observable<any>;
public getUser(){
users$ = this.jobService.getUsers();
}
并在您看来:
<div *ngFor='let user of users | async'>
<p>{{user.id}}</p>
<p>{{user.name}}</p>
<p>{{user.email}}</p>
<p>{{user.url}}</p>
<h2>groups:</h3>
<div *ngFor='let group of user.groups'>
<p>{{group.id}}</p>
<p>{{group.name}}</p>
<p>{{group.url}}</p>
<h3>Permissions:</h3>
<div *ngFor='let permission of group.permissions'>
<p>{{permission}}</p>
</div>
</div>
</div>
答案 3 :(得分:0)
我的json数据是这个
(0.3*b+0.1333333)/(0.7)
在一个有角度的模板中,我得到了这样的数据
"orders": [
{
"totalPrice": 1200,
"_id": "5cf0b8fd245b7904440aa4b7",
"products": [
{
"quantity": 1,
"_id": "5cf0b8fd245b7904440aa4b8",
"product": {
"reviews": [
"5cf0b8a8245b7904440aa4b6"
],
"_id": "5ce83a9c16bec823d4bddff9",
"crated": "2019-05-24T18:40:28.253Z",
"owner": "5cc2f1c195d5a13018080651",
"category": "5cc62714304f84437059eada",
"title": "book",
"price": 12,
"description": "aaaaaaaa",
"image": "uploads\\1558723228216-direct-to-other-schema.png",
"__v": 1,
"averageRating": null,
"id": "5ce83a9c16bec823d4bddff9"
}
}
],