Home > Enterprise >  Proper way to pass date objects between a javascript/typescript frontend and a ASP.net Core 5 backen
Proper way to pass date objects between a javascript/typescript frontend and a ASP.net Core 5 backen

Time:11-16

I'm developing a web application where the backend is a REST web API written in ASP.net Core 5 and the frontend is an Angular application written in TypeScript.

One of my ASP.net backend APIs returns an instance of this C# object:

public class MyClass
{
  DateTime expires {get; set;}
  string ticket {get; set;}
}

In my Angular app, I call this API with Angular's HTTP Client and deserialize the result as an instance of the following TypeScript class:

export class MyClass
{
  expires: Date;
  ticket: string;
}

However, this doesn't work properly because because if I inspect the TypeScript object once it has been returned I can see that the expires field actually contains a string, not a Date object.

I imagine this happens because the data travels between backend and frontend in JSON format, which doesn't support types but only knows about strings and numbers, so the C# DateTime object is converted to a string.

My question is: what is the best way to handle this problem? I would like to keep my objects strongly typed if possible... is there some configuration I can do on the ASP.net and/or Angular side so that this kind of serialization works automatically? Or if not, what is the next best approach?

CodePudding user response:

This is the solution I put together from the suggested answers in the comments:

return this.http.get<MyClass>(restUrl, { observe: 'response' })
      .pipe(map(response => {
        if (response.ok) {
          response.body.expires = new Date(response.body.expires);
          this.setLoginResult(response.body);
        }
        return response;
      }));
  • Related