Angular 2 observable doesn't 'map' to model

Viewed 12266

As I'm learning Angular 2 I used an observable to fetch some data via an API. Like this:

getPosts() {
        return this.http.get(this._postsUrl)
            .map(res => <Post[]>res.json())
            .catch(this.handleError);
    }

My post model looks is this:

export class Post {

constructor(
    public title: string,
    public content: string,
    public img: string = 'test') {
}

The problem I'm facing is that the map operator doesn't do anything with the Post model. For example, I tried setting a default value for the img value but in the view post.img displays nothing. I even changed Post[] with an other model (Message[]) and the behaviour doesn't change. Can anybody explain this behaviour?

2 Answers

You can use the as keyword to de-serialize the JSON to your object.

The Angular2 docs have a tutorial that walks you through this. However in short...

Model:

export class Hero {
  id: number;
  name: string;
}

Service:

...
import { Hero } from './hero';

...
get(): Observable<Hero> {
    return this.http
               .get('/myhero.json')
               .map((r: Response) => r.json() as Hero);
}

Component:

get(id: string) {
    this.myService.get()
      .subscribe(
        hero => {
          console.log(hero);
        },
        error => console.log(error)
      );
}
Related