Reputation: 8731
I made a simple Http call:
http.get('/test/data/user.json').
map(res => <User> res.json()).
subscribe(user => {
console.log(typeof user);
console.log(user);
console.log(user.getName());
});
with the following data in user.json
:
{
"name":"Robert"
}
and the following User
class:
export class User{
name:string;
lastName:string;
getName():string{
return this.name;
}
}
Problem is the result I get in console:
console.log(typeof user);
object
console.log(user);
Object {name: "Robert"}
console.log(user.getName());
Uncaught TypeError: user.getName is not a function
Problem here is that my object is an object
, not a User
, so it does not have all properties, and it has no methods.
Also tried with Promise-based call and user.json() as User
instead of <User> res.json()
EDIT: not similar to casting to an interface since interface doesn't have its own behaviour.
Upvotes: 4
Views: 1523
Reputation: 202326
If you want to use the getName
method, you need to instantiate an new User
object when mapping the response body:
http.get('/test/data/user.json').
map(res => {
let body = res.json();
return new User(body.name, body.lastName);
})
subscribe(user => {
console.log(typeof user);
console.log(user);
console.log(user.getName());
});
The User
class would be adapted like below:
export class User{
constructor(private name:string, private lastName:string) {}
getName():string{
return this.name;
}
}
Casting an object won't add method to an existing object. The json
method of the response will simply parse the response body using JSON.parse
and return a raw object.
See this plunkr: https://plnkr.co/edit/7lKHvArpayrMAzm5Xgk1?p=preview.
Upvotes: 3