Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
Angular/Typescript - Parse Response to Interface

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 :-)

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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));
over 4 years ago · Santiago Trujillo Denunciar

0

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) })
  );
over 4 years ago · Santiago Trujillo Denunciar

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda