Florin Simion Florin Simion - 2 days ago 5
TypeScript Question

Angular 2 Array printed on console but can't print object property on screen

I have the following method in a service I've created:

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);
});
}


And this is the class of my component:

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);
});

}

}


The JSON feed looks like this(yes one object in the array):

[
{
"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"
}
]


So in my template, if I print
{{post}}
I get [object Object] on the screen.

If I print
{{post | json}}
I get the row JSON feed.

And finally, if I print
{{post.title}}
or
{{post?.title}}
I don't get anything.

I also have a class Post that is looking like this:

export class Post{
constructor(

public nid?: string,
public title?: string,
public body?: string
public image?: string
){
}
}


Any hints?

Answer

You are assigning an array into what should be a single object. Copy the first element of the array into the post variable

this.post = res[0] as Post

Side note: It's incorrect to assign an object to a class instance. In this case, your this.post.constructor won't exist and this.post instanceof Post == false. You could do Object.assign(this.post, res[0]) but you may need to clear existing properties if not all properties are always present

Comments