Best practices for transferring date objects between a frontend developed in JavaScript/TypeScript and a backend built in ASP.net Core 5

An exciting project I am working on involves a web application with a backend REST web API developed in ASP.net Core 5 and a frontend Angular application written in TypeScript.

One of the APIs from the ASP.net backend returns an instance of a C# object defined as:

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

When calling this API from my Angular app using Angular's HTTP Client, I deserialize the result as an instance of the following TypeScript class:

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

Unfortunately, there seems to be an issue as upon inspecting the TypeScript object after it is returned, it shows that the 'expires' field holds a string instead of a Date object.

This discrepancy may be due to the fact that data travels between the backend and frontend in JSON format, which only recognizes strings and numbers and not types, leading to the conversion of the C# DateTime object to a string.

My main concern is how to address this challenge effectively. Ideally, I would like to maintain strong typing for my objects. Is there a way to configure the serialization process automatically on the ASP.net and/or Angular side to resolve this issue? If not, what alternate approach should I consider?

Answer №1

Here is the finalized solution that incorporates the feedback provided in the comments:

fetchDataFromUrl(apiEndpoint) {
      return this.http.get<MyClass>(apiEndpoint, { observe: 'response' })
          .pipe(map(response => {
              if (response.ok) {
                  response.body.expires = new Date(response.body.expires);
                  this.updateLoginStatus(response.body);
              }
              return response;
          }));
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble encountered when attempting to upload a file with PhantomJs (and Selenium WebDriver)

My Current HTML Setup: Initially, my HTML code looks like this: <form action="http://example.com/upload_photo_iframe.html" preview_div="upload_photo_div" submit_button="submit_btn" upload_field="photo_upload" target="photo_target" enctype="multipart/f ...

Utilizing the namespace importation method correctly

How can I efficiently utilize classes from a namespace that may be the same or different from the current file's namespace? I currently have the following two files. TypeA.ts: export namespace Game { @ccclass export class TypeA extends cc.Component ...

Updating a boolean value when the checkbox is selected

Hey there! I'm currently working on a project using Angular and have a collection of elements that can be checked, which you can check out here. In terms of my business logic: stateChange(event: any, illRecipe: Attendance){ var state: State = { ...

Combining URL parameters into an object with NestJS's HTTP module

Is there a method for passing URL parameters to the httpService in nestjs? I want to improve the readability of this URL without resorting to Axios as nest has its own HTTPModule. Currently, this is how it looks and functions: const response = await this. ...

How can one retrieve a file in Silverlight without using Webclient?

I'm faced with a challenging task of downloading one file into a ByteArray, editing the ByteArray, simultaneously downloading another large file, merging the first edited file into it on-the-fly, and playing it using MediaElement. Although I can down ...

Merging RXJS observable outputs into a single result

In my database, I have two nodes set up: users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}} homework: {user1: {homeworkAnswer: "Sample answer"}} Some users may or may not have homework assigned to them. ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

Choosing and unchoosing columns in an Angular Material table

Feel free to check out this link for more information: Angular PrimeNG Table Order Resize Toggle. It provides guidance on how to select and deselect columns in Angular Mat table. ...

How to retrieve a value from ng-options using AngularJS?

I want to display a dropdown in which users can select a specific month. Currently, the dropdown is populated with all 12 months in an array. How can I make sure that only the selected month is fetched from the dropdown? Code Snippet: $scope.Month = [&ap ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

Determine if an element in Angular 6 contains a particular style

Below is a div, and the first time you click on it, an opacity style is added. I am looking to determine within the same function if this div has an opacity style set to 1. @ViewChild('address') private address: ElementRef; public onClickAddres ...

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

The post method is throwing an error 405, indicating that it does not support the HTTP GET method

I am facing an issue with my asp.net framework api endpoint that is throwing an error on IIS. The API endpoint is a post method and the code looks like this: [HttpPost] [Route("api/ebonyiproxy/validateexpectedpaymentref")] public asyn ...

Tips for avoiding Angular routing when clicking on a Bootstrap tab link

I'm working on creating a bootstrap tab, but I'm running into an issue. Every time I click on the tab links, angular seems to be handling its own routing and redirecting me to a different route. What I really want is for the tab content to open u ...

Issues with loading image assets on GitHub Pages after deploying in production with Angular2, Angular-cli, and Webpack

This is NOT a repeated query: This particular issue presents the problem, but it pertains to a project not built with angular-cli like mine does, hence a webpack.config file is absent. While my described dilemma involves accurately configuring the base_u ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

Experiencing difficulties establishing a connection with my NodeJs server socket and TypeScript

I've been struggling to run the code from this post and I really need some help. The code can be found at: https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c. I liked the code as it seems suitable for large projects, but ...

Unveiling the Mysteries of HTTP Headers in Angular

Seeking a way to retrieve a token set in the http header within my Angular application. This is how my Angular application is being served: var express = require('express'); var app = express(); var port = process.env.PORT || 3000; var router = ...

Can you identify a specific portion within an array?

Apologies for the poorly titled post; summarizing my query into one sentence was challenging. I'm including the current code I have, as I believe it should be easy to understand. // Constants that define columns const columns = ["a", " ...

Exploring deep object structures in C#

My current challenge involves extracting specific details from an object using the Google Books API. To achieve this, I have deserialized the content into two POCOs in order to access a nested object. My main hurdle lies in retrieving properties such as ti ...