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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.