当我想在模板中使用计算属性时,我遇到了类似的问题。
我在本文中找到了一个很好的解决方案:
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); }}


