Angular 2 Observable不会“映射”到模型

Angular 2 Observable不会“映射”到模型,第1张

Angular 2 Observable不会“映射”到模型

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

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

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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5662441.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存