M
M
mitaichik2018-04-10 01:58:37
Angular
mitaichik, 2018-04-10 01:58:37

How to cast an HttpClient response to a specific type?

Just started learning Angular.
It is necessary that the HttpClient response return object instances, for example, there is a method:

getPersons(): Observable<Person[]> {
    return this.http.get<Person[]>("http://test/api/v1/persons");
  }

Well, I expect that it will return me an Observable with a list of instances of the Person class. That is, he himself will create Person instances and shove data there (as, for example, retrofit does) But in fact there is an array of Object. Can't Angular out of the box do that?
Yes, it's worth noting that Person is not an interface, but a class that has methods. Accordingly, I want to get a person, call the person.someMethod() method - and it gives me an error (since it is an Object)
Thanks in advance.
UPDATE
Figured out how to do:
getPerson(id: number): Observable<Person> {

    let config = {params: {id: id.toString()}};

    return this.http
      .get<Person>("http://test/api/v1/person/view", config)
      .pipe(map(p => {
        let person = new Person();
        Object.assign(person, p);
        return person;
      }))
  }

But can't Angular do that out of the box?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitrygavrish, 2018-04-10
@mitaichik

Angular has nothing to do with it, it cannot create a class instance based on the type specified in the generic, because this is a type, not a class constructor.
Any such example in typescript will cause an error:

function someFunction<T>(): T {
    return new T();
}

P.S. In your case, you can make it a little more concise:
return this.http
    .get<Person>("http://test/api/v1/person/view", config)
    .map(p => new Person(p));

Only for this, the constructor of the Person class must be able to write to itself inside the property from the object passed to the constructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question