I have recently developed a basic application using the Angular2 tutorial as my guide.
Initially, I established a straightforward "Book" model:
/**
* Definition of book model
*/
export class Book {
public data;
/**
* Constructor for Book class
* @param id
* @param title
* @param pages
*/
constructor(
public id,
public title:string,
public pages:Array
){
alert('it works'); // just a sanity check
}
}
Within my service, I retrieve a book in the following manner:
return this._http.get('getBook/1')
.map(function(res){
return <Book> res.json();
})
My initial assumption was that this code snippet would convert the JSON data received into a Book object.
However, the output is merely an object with the type "Object."
To resolve this issue, I manually create a new Book object and provide the necessary parameters to its constructor, as shown below:
return new Book(res.id, res.title, res.pages);
Is this approach optimal? Have I overlooked any better alternatives?