I recently migrated my Angular app to use the new HttpClient, but I'm encountering some challenges in achieving the same results as before with Http. Can anyone help me out?
Here's what I was doing with Http:
getAll() {
return this.http.get(environment.API_DOMAIN + environment.CURRENCY_API_URL).map(res => {
let response: ICurrenciesResponse = <ICurrenciesResponse> res.json();
response.result = <Currency[]> res.json().result.map(service => {
return new Currency(<ICurrency> service);
});
return response;
});
}
The response is typed using the interface ICurrenciesResponse which looks like this:
import { IGenericResponse } from '../igeneric-response';
import { Currency } from '../../classes/currency';
export interface ICurrenciesResponse extends IGenericResponse {
result?: Currency[]
}
As you can see, the interface extends IGenericResponse and consists of an array of Currency objects. To properly set this array, I had to map it again to create new Currency objects. This method worked well for me.
Now, after switching to HttpClient, my getAll function looks like this:
getAll(): Promise<ICurrenciesResponse> {
return this.http
.get<ICurrenciesResponse>(environment.API_DOMAIN + environment.CURRENCY_API_URL)
.toPromise();
}
However, now my Currency array is not being properly set as an array of Currency objects. Shouldn't HttpClient automatically cast the data based on the defined interface in the get method? If not, what would be the best approach to achieve the same functionality as before with Http? Should I use subscribe() instead of toPromise() and process the data in a similar manner as before?
Thank you in advance!