Angular 2 observable doesn't 'map' to model

后端 未结 2 982
青春惊慌失措
青春惊慌失措 2020-12-16 04:35

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)
                  


        
相关标签:
2条回答
  • 2020-12-16 04:57

    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)
          );
    }
    
    0 讨论(0)
  • 2020-12-16 05:06

    I had a similar issue when I wanted to use a computed property in a template.

    I found a good solution in this article:

    http://chariotsolutions.com/blog/post/angular-2-beta-0-somnambulant-inauguration-lands-small-app-rxjs-typescript/

    You create a static method on your model that takes an array of objects and then call that method from the mapping function. In the static method you can then either call the constructor you've already defined or use a copy constructor:

    Mapping Method

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

    Existing Constructor

    export class Post {
      // Existing constructor.
      constructor(public title:string, public content:string, public img:string = 'test') {}
    
      // New static method.
      static fromJSONArray(array: Array<Object>): Post[] {
        return array.map(obj => new Post(obj['title'], obj['content'], obj['img']));
      }
    }
    

    Copy Constructor

    export class Post {
      title:string;
      content:string;
      img:string;
    
      // Copy constructor.
      constructor(obj: Object) {
        this.title = obj['title'];
        this.content = obj['content'];
        this.img = obj['img'] || 'test';
      }
    
      // New static method.
      static fromJSONArray(array: Array<Object>): Post[] {
        return array.map(obj => new Post(obj);
      }
    }
    

    If you're using an editor that supports code completion, you can change the type of the obj and array parameters to Post:

    export class Post {
      title:string;
      content:string;
      img:string;
    
      // Copy constructor.
      constructor(obj: Post) {
        this.title = obj.title;
        this.content = obj.content;
        this.img = obj.img || 'test';
      }
    
      // New static method.
      static fromJSONArray(array: Array<Post>): Post[] {
        return array.map(obj => new Post(obj);
      }
    }
    
    0 讨论(0)
提交回复
热议问题