I had a similar problem 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 in your model that takes an array of objects and then calls this method from the map function. In the static method, you can either call the constructor that you already defined, or use the copy constructor:
Matching 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 use 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;
source share