0

I have an api that returns ISO date that needs to be transformed into javascript date. I am using the HTTPClient module that does the mapping automatically but it seems it is not transforming the data received.

I know that it works if I do it using the http module but I want to use the HTTPClient.

My Code is below.

   export class Product{
     datetime: string;
     qty: number;
     constructor(date: string, hr: number )  {
        this.datetime = new Date(Date.parse(date));
        this.heartrate = hr;
       }
     }



    @Injectable()
    export class BandHeartRate {

        private Url  = 'http://192.168.1.1:6000';
        constructor(private http: HttpClient) {}

    public getProduct(): Observable<Product[]> {

            return this.http.get<Product[]>(`${this.Url}/web/api/v2/product`, 
    {headers: this.getHeader()});

        }

        private getHeader() {
            const header = new HttpHeaders();
            header.append('Accept' , 'application/json');
            return header;
        }
    }
    }
1
  • where do you subscribe to getProduct()? Where are you calling your Product class? Commented Nov 20, 2017 at 4:35

1 Answer 1

1

The response to your http call will be a JSON object. JSON has no representation of dates per se, so your dates will be represented as strings in the result. You have correctly recognized that you will need to transform these strings into dates manually.

Your code is roughly correct, but you are assuming that you can just cast the JSON returned into a Product instance. That will not work. It would work if Product was an interface, not a class (to create an instance of a class you need to call its constructor and your code is not doing that anywhere).

One quick fix is to change your calling code as follows:

this.http.get(`${this.Url}/web/api/v2/product`, 
    {headers: this.getHeader()})
.map(productList => productList.map(productJson => new Product(productJson)));

This constructs Product instances using the JSON received (the first map says you want to transforms the result of the Observable, the second map transforms each item in your JSON array from JSON to Products).

The Product constructor will receive the JSON for a single object, so you would need to modify it slightly too:

export class Product {
    date: Date
    hr: number

    constructor({dateAsString, hr})  {
        this.date = new Date(dateAsString);
        this.hr = hr
    }
}

If you're wondering about the ({dateAsString, hr}) syntax, google "function parameter destructuring".

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

3 Comments

What I don't understand is the initial Product class where it does not execute the constructor that the HttpClient is subscribed.
Yeah, it's the get<Product[]> that can be confusing. This doesn't actually change the JSON returned in anyway, it just treats it as if it was of this type. It's like the as keyword. This is quite dangerous, because you specify the wrong type (like in this case Product[]) you will believe that it's actually Product instances, but it's really not. It's really intended to be used only with interfaces. It's fine to treat an object (that has the right structure) as an interface, but if an object instance is not of a certain type, you cannot treat it as another type.
I think for Typescript to be faking and making things along the way is confusing. OK, how do I transform the data using interface. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.