Reputation: 358
I am using angular 2 and I am trying to call an endpoint to return a collection of objects.
I have the following TypesScript class
export class Route
{
public branchId: number;
public branch: string;
public isTest: boolean = true;
}
I have a api endpoint which returns the following Json
[{"id":610,"branch":"Coventry"},{"id":620,"branch":"Shoreham"}]
I have a route service which calls the endpoint using the following code
public getRoutes(): Observable<Route[]>
{
const url = 'http://localhost/routes';
return this.http.get(url)
.map((response: Response) =>
{
const routes: Route[] = response.json() as Route[];
if (routes.length > 0) {
console.log(routes[0].isTest);
//This returns undefined I was expecting the boolean value true
}
return routes;
}
)
.catch(e => this.httpErrorService.handleError(e));
}
It appears that the response.json() is not being cast to data type Route. Why is this?
Upvotes: 1
Views: 1103
Reputation: 14221
You cannot do a strict cast like that in TypeScript and have the objects become that type. The cast is simply a transpiler trick to tell the rest of your code that you are working with a Route
array. To truly get the json data to be of type Route
and not just Object
you can use the assign
method to type them like so:
const routes: Route[] = (response.json() as []).map((obj) => {
return Object.assign(new Route(), obj);
}) as Route[];
If the json data does have all of the properties set then there is no need to use the assign
method because at that point you are developing against an interface which should work as if you were working with the typed object.
Upvotes: 4