Search code examples
angulartypescripthttpclient

Angular httpClient map response to entity with behaviour


I'm trying to map the response of my GET-request to an entity-class. When calling a function on that response-object an error is thrown:

TypeError: res.foo is not a function

GET-Request:

 this.http.get<TodoEntity>('https://jsonplaceholder.typicode.com/todos/1').subscribe((res) => {
    console.log(res.foo());
  })

Entity-Class:

export class TodoEntity {
 public userId: number;
 public id: number;
 public title: string;
 public completed: boolean;
 public foo(): string {
    return 'Hello world';
 }
}

Is there a way to map the response directly to an entity class and call a function on it? Or do I have to manually create a new instance of TodoEntity based on the response-object?

I'm using typescript 3.1.6 with angular 7.3.6.


Solution

  • You need to create an instance of the class. The methods are not available when you cast your JSON into prototypical JavaScript/ TypeScript class.

    Edit: Just found a good explanation here: https://stackoverflow.com/a/22875957/894532