Florin Simion Florin Simion - 1 year ago 91
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();
private route: ActivatedRoute,
private postService: PostService
) { }
ngOnInit() {

this.route.params.switchMap((params: Params) => {
let nid = params ['nid'];
return this.postService.getPost(nid); }).subscribe(res => {
this.post = res as Post;
}, err =>{



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

"title":"When Unity meets Vuforia",
"body":"<p>Unless you have been living under a rock in the past 7 - ...",

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

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

And finally, if I print
I don't get anything.

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

export class Post{

public nid?: string,
public title?: string,
public body?: string
public image?: string

Any hints?

Answer Source

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