Angular4 migrate from Http to HttpClient

1.2k views Asked by At

I'm migrating my Angular app to use now the new HttpClient but I'm having some problems to achieve the same result I was getting with Http. Hope you guys can help me out.

So 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 with the interface ICurrenciesResponse witch 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 is composed by an array of Currency witch is a defined class. In order to have this array properly setted I had to do the secound map where then I create a new Currency object. This works perfectly and I'm very happy with the method so far.

Know, when I migrate to HttpClient I have this:

getAll(): Promise<ICurrenciesResponse> {
    return this.http
        .get<ICurrenciesResponse>(environment.API_DOMAIN + environment.CURRENCY_API_URL)
        .toPromise();
}

But know my Currency array is not properly setted as an array of Currency's. Wasn't HttpClient suppose to cast the data according to the interface defined as a type on the get method? If not, what's the best way to achieve the same I did with Http? Use subscribe() in stead of toPromisse() and process the data the same way I'm already doing?

Thanks in advance!

1

There are 1 answers

0
cyr_x On BEST ANSWER

The HttpClient tries to find the right content-type for the response, it's not creating instances for you from data inside the response.

You still have to use the map operator and create the instances inside it. But you have to remove the .json() call.

getAll() {
    let url = environment.API_DOMAIN + environment.CURRENCY_API_URL;
    return this.http
        .get<ICurrenciesResponse>(url)
        .map(response => {
            if(Array.isArray(response.result) {
              response.result = response.result.map(service => new Currency(service));
            }
            return response;
        });
}