2

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.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

2 Answers2

3

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

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
1

You can use the RxJS' map operator to build a TodoEntity instance from the set of properties returned by the webservice, using Object.assign:

this.http.get('https://jsonplaceholder.typicode.com/todos/1').pipe(
  map(res => Object.assign(new TodoEntity(), res))
).subscribe((res: TodoEntity) => {
  console.log(res.foo());
});

Demo: https://stackblitz.com/edit/angular-igaw2q

Jeto
  • 14,596
  • 2
  • 32
  • 46