Answer the question
In order to leave comments, you need to log in
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");
}
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;
}))
}
Answer the question
In order to leave comments, you need to log in
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();
}
return this.http
.get<Person>("http://test/api/v1/person/view", config)
.map(p => new Person(p));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question