2

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?

0

1 Answer 1

2

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 a raw 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.

I prefer to define object shapes as interfaces instead, then you would not have that problem because all the interface information is removed at runtime, whereas a class does emit some code instead of just doing static type checks at compilation time

Sign up to request clarification or add additional context in comments.

2 Comments

That was what I needed...thank you, Juan. Would be nice if you can point me to an place where I can read more about this.
Read more about what? Assigning an array where an object is expected and masking the error because you cast it? Not sure what part is unclear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.