Angular 2 observable不会"映射"到模型

Jen*_*the 6 observable angularjs

当我正在学习Angular 2时,我使用了一个observable来通过API获取一些数据.像这样:

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

我的帖子模型看起来是这样的:

export class Post {

constructor(
    public title: string,
    public content: string,
    public img: string = 'test') {
}
Run Code Online (Sandbox Code Playgroud)

我面临的问题是地图运算符对Post模型没有任何作用.例如,我尝试为img值设置默认值,但在视图post.img中没有显示任何内容.我甚至用另一个模型(Message [])更改了Post [],并且行为没有改变.任何人都可以解释这种行为吗?

小智 13

当我想在模板中使用计算属性时,我遇到了类似的问题.

我在本文中找到了一个很好的解决方案:

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

您在模型上创建一个静态方法,该方法接受一个对象数组,然后从映射函数中调用该方法.在静态方法中,您可以调用已经定义的构造函数或使用复制构造函数:

映射方法

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

现有的构造函数

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']));
  }
}
Run Code Online (Sandbox Code Playgroud)

复制构造函数

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是支持代码完成的编辑器,则可以将objarray参数的类型更改为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);
  }
}
Run Code Online (Sandbox Code Playgroud)