我在创建的服务中有以下方法:
getPost(nid: string): Observable<Post[]>{
let url = "http://test.co.uk/api/v1/basic/" + nid;
return this.http.get(url, {headers: this.headers}).map(res => res.json() as Post).catch(err => {
return Observable.throw(err);
});
}
这是我的组件的类:
export class PostDetailComponent implements OnInit {
posts: Post[] = [];
post: Post = new Post();
constructor(
private route: ActivatedRoute,
private postService: PostService
) { }
ngOnInit() {
this.route.params.switchMap((params: Params) => {
let nid = params ['nid'];
return this.postService.getPost(nid); }).subscribe(res => {
console.log(res)
this.post = res as Post;
}, err =>{
console.log(err);
});
}
}
JSON 提要如下所示(是的,数组中的一个对象):
[
{
"nid":"3",
"title":"When Unity meets Vuforia",
"body":"<p>Unless you have been living under a rock in the past 7 - ...",
"uid":"admin",
"path":"\/node\/3",
"field_article_image":"http:\/\/test.co.uk\/sites\/default\/files\/when-unity-meets-vuforia_0.jpg?itok=BGYaotay"
}
]
因此,在我的模板中,如果我打印 {{post}}
我会在屏幕上看到 [object Object]。
如果我打印 {{post | json}}
我得到行 JSON feed。
最后,如果我打印 {{post.title}}
或 {{post?.title}}
我什么也得不到。
我还有一个类帖子,如下所示:
export class Post{
constructor(
public nid?: string,
public title?: string,
public body?: string
public image?: string
){
}
}
有什么提示吗?
最佳答案
您正在将一个数组分配给应该是单个对象的对象。将数组的第一个元素复制到 post 变量
this.post = res[0] as Post
旁注:将原始对象分配给类实例是不正确的。在这种情况下,您的 this.post.constructor
将不存在,并且 this.post instanceof Post == false
。
您可以执行Object.assign(this.post, res[0])
,但如果并非所有属性始终存在,您可能需要清除现有属性。
我更喜欢将对象形状定义为接口(interface),那么您就不会遇到这个问题,因为所有接口(interface)信息都会在运行时删除,而类确实会发出一些代码,而不仅仅是在编译时进行静态类型检查
关于javascript - Angular 2 数组打印在控制台上,但无法在屏幕上打印对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909313/