尝试将数据从json绑定到模型,并且无法弄清楚。它显示[对象对象],[对象对象],[对象对象]。 尝试{{post.comments.text}}没有显示任何内容..
JSON
{
"id": "507033622",
"author": {
"user": 2,
"name": "test",
"avatar": null,
"bio": "",
"banned": false
},
"subscribed": true,
"created": "2017-06-21T19:45:46.289429Z",
"active": true,
"text": "Lolololol",
"comments": [
{
"id": 1,
"author": {
"user": 1,
"name": "wyldbot",
"avatar": null,
"bio": "",
"banned": false
},
"created": "2017-06-24T14:06:28.861325Z",
"text": "Comment"
},
{
"id": 2,
"author": {
"user": 1,
"name": "wyldbot",
"avatar": null,
"bio": "",
"banned": false
},
"created": "2017-06-24T14:30:43.382514Z",
"text": "More data"
},
{
"id": 3,
"author": {
"user": 1,
"name": "wyldbot",
"avatar": null,
"bio": "",
"banned": false
},
"created": "2017-06-24T14:30:53.115687Z",
"text": "More data"
}
]
}
post.ts:
import { Injectable } from '@angular/core';
import {Author} from "./author";
import {Comment} from "./comment";
@Injectable()
export class Post {
id:number;
author:Author;
subscribed:boolean;
created:string;
active:boolean;
text:string;
comments:Comment[];
constructor(id:number, author:Author, subscribed:boolean, created:string, active:boolean, text:string, comments:Comment[]) {
this.id = id;
this.author = author;
this.subscribed = subscribed;
this.created = created;
this.active = active;
this.text = text;
this.comments = comments;
}
public static getPosts():Post{
return new Post(0, null, null, "", null, "",null);
}
}
comment.ts
import { Injectable } from '@angular/core';
import {Author} from "./author";
@Injectable()
export class Comment {
id:number;
author:Author;
created:string;
text:string;
constructor(id:number, author:Author, created:string, text:string) {
this.id = id;
this.author = author;
this.created = created;
this.text = text;
}
public static createBlankComment():Comment{
return new Comment(0, null, "", "");
}
}
home.component.html
<h3>Post ID: {{post.id}}</h3>
<p>Post Owner ID: {{post.author.user}}</p>
<p>Post Owner Name: {{post.author.name}}</p>
<p>Post Owner Avatar: {{post.author.avatar}}</p>
<p>Post Owner Bio: {{post.author.bio}}</p>
<p>Is Post Owner Banned: {{post.author.banned}}</p>
<p>Subscribed: {{post.subscribed}}</p>
<p>Created: {{post.created}}</p>
<p>Active: {{post.active}}</p>
<p>Text: {{post.text}}</p>
<p>Comments: {{post.comments}}</p>
答案 0 :(得分:1)
由于post.comments是一个数组,因此使用*ngFor
指令循环它。
<div *ngFor="let comment of post.comments">
<div>Text: {{ comment.text }}</div>
</div>
我已经介绍了在plnkr中从json访问数据的其他案例。
<div *ngFor="let comment of post.comments">
<p>Comment: {{ comment | json}}</p>
<p>Author: {{ comment.author | json}}</p>
<p>Author Name: {{ comment.author.name }}</p>
<p>Text: {{ comment.text }}</p>
</div>