angularjs - Angular 2 observable 不是 'map' 来建模

标签 angularjs observable

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

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

我的帖子模型看起来是这样的:
export class Post {

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

我面临的问题是 map 操作符不会对 Post 模型做任何事情。例如,我尝试为 img 值设置默认值,但在 View post.img 中什么也没显示。我什至用其他模型 (Message[]) 更改了 Post[] 并且行为没有改变。有人可以解释这种行为吗?

最佳答案

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

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

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);
}

现有构造函数
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']));
  }
}

复制构造函数
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);
  }
}

如果您使用支持代码完成的编辑器,您可以更改 obj 的类型。和 array 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);
  }
}

关于angularjs - Angular 2 observable 不是 'map' 来建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36150709/

相关文章:

angular - Concat 可观察对象

c# - 我们如何在 IObservable<T> 上使用组函数,同时观察未完成或在热的、长时间运行的可观察对象上

Angular observables - 如果没有订阅,我是否需要取消订阅?

javascript - 在 css 中评价星星不起作用

javascript - 如何重定向到 SPA 中带有下拉菜单的页面?

javascript - AngularJS 不读取 REST 上的 Iframe 元素

javascript - 对后端的调用在服务内部可以正常工作,但在服务外部则不行

angular - 如何从Angular 2/Ionic 3中的多个Observables执行错误处理?

javascript - AngularJS:不允许在 Angular 表达式中引用 DOM 节点

javascript - 带有 JSON 对象数组过滤器的 Angular JS Controller