Home > Blockchain >  Angular/Typescript - Parse Response to Interface
Angular/Typescript - Parse Response to Interface

Time:09-29

i have a the following Interface

interface MyObj {
    myString: string;
    myNumber: string;
    myDate: Date;
}

this.http.get<MyObj>(this.getObjectsURL);
Result: 
  { "myString": "test", "myNumber": 12, "myDate": "2011-10-05T14:48:00.000Z"}

If i get the data, the field myDate is a string and not a Date.

If i transform MyObj to a JSON and parse it again, i get a Date-String too, and not the correct Type. Thats very bad :-( Is it possible to parse typesafe ( for HTTP requests and Json Transform, too?) with transformation to the right data-types?

Thanks :-)

CodePudding user response:

You can add a pipe to transform response when it is received.

Create as service to make all api calls inside service

getYourObject() {
    return this.http.get(this.getObjectsURL)
      .pipe(map(resp => {
        resp.myDate = new Date(resp.myDate);
        return data;
      }));
  }

from your component and add service as dependancy then

this.serviceName.getYourObject().subscribe((resp: MyObj)=> console.log(resp));

CodePudding user response:

Basically you have two types, an external/serialized representation and internal/non-serialized,

interface MyObj {
    myString: string;
    myNumber: string;
    myDate: Date;
}

interface MyObjSerialized {
    myString: string;
    myNumber: string;
    myDate: string;
}

You can use the first type to annotate the result from the http.get call

const result: Observable<MyObjSerialized> = 
  this.http.get('http://some.where');

Next you need to explicitly parse it and convert it to the internal data type:

const parsed: Observable<MyObj> = 
  result.pipe(
    // alternative: provide a method reference instead of arrow function
    // angular brackets <From,To> optional
    map<MyObjSerialized, MyObj>(res => ({ ...res, myDate: new Date(res.myDate) })
  );

CodePudding user response:

I found this Library: https://github.com/pichillilorenzo/jackson-js Maybe this is my solution.. I will test it!

  • Related