The object's date field is being assigned a data type of Long

When I send a LocalDateTime field as Long type from Spring Boot, it is not deserialized in Angular and remains as long instead of being converted to Date.

Is there a universal deserialization setting for this in Angular? I am looking for a solution without having to manually convert the field using new Date(field_name).

JSON data sent from Spring Boot

..."field_1":1666256336000...

Angular model

export class Object1 {
        field_1: Date;
}

Angular Service Method

method_name(){
    return this.getHttp().get<Object1>(..urls..);
}

We call the method

this.service.method_name().pipe().subscribe((data: Object1) => {
            console.log(data.field_1)
        });

The output appears like this

1666256336000

Answer №1

To effectively handle incoming data and convert a Long timestamp into a Date object in Angular, you would require the implementation of an Interceptor. This Interceptor would intercept the incoming data, extract the Long timestamp representing milliseconds, and transform it into a Date object.

Within your Interceptor, you would utilize the new Date(value) constructor of the JavaScript Date Object, which is capable of processing timestamps in milliseconds.

If you were to create such an Interceptor, it might resemble the following code snippet:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpResponse, HttpRequest, HttpHandler } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class DateFormatInterceptor implements HttpInterceptor {
  intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(httpRequest).pipe(
       map((response: HttpResponse<any>) => {
          let formatted = response.clone();
          for(let key in formatted){
             if(key == "date1" || key == "date2" || key == "date3"){
                formatted[key] = new Date(formatted[key]);
             }
          }
          return formatted;
       }
     );
  }
}

Remember to provide this Interceptor within your application as well.

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

Altering the properties of a specified element within TestBed using the overrideComponent method

We are implementing TestBed.overrideComponent() to substitute a component with custom behavior. TestBed.overrideComponent(CoolComponent, { set: { template: '<div id="fake-component">i am the fake component</div>', sel ...

At what point is it appropriate for a class to incorporate an interface?

Currently working on a project and I've noticed developers using TypeScript in the following way: export class Ledger implements ILedger { LedgerID: number; CashAmmount: number; Units: number; ...

Getting access to a JavaScript class from TypeScript and initializing it

I have integrated jsPDF by adding its jspdf.min.js file to my project. However, I am facing an issue when trying to use it within a TypeScript class. The error message states that jsPDF is unknown: btnPrintReportClick() { var pdf = new jsPDF(); ...

Error in Typescript: TS7006 - The parameter 'xxx' is assumed to have a type of 'any' without explicit declaration

When testing my UserRouter, I am utilizing a json file data.json [ { "id": 1, "name": "Luke Cage", "aliases": ["Carl Lucas", "Power Man", "Mr. Bulletproof", "Hero for Hire"], "occupation": "bartender", "gender": "male", "height" ...

Issue: Unhandled promise rejection: SecurityError: To use screen.orientation.lock(), the page must be in fullscreen mode

While attempting to change the orientation of one of my pages in an Ionic 3 app, I encountered the following error. The code snippet below was used to change from portrait mode to landscape mode: ionViewDidEnter() { // this.statusBar.hide(); // // ...

Error encountered during the http.put() method due to invalid request payload

I'm currently using HttpClient from '@angular/common/http' to perform a PUT operation. Here is the Angular code snippet I am working with: public updateDetails(data: Data) { const url = '/project/rest/v1/configuration/device/upd ...

Using Angular's mat-sidenav component to create a navigation menu that

I am looking to create a webpage similar to Ryanair's checkout process at www.ryanair.com/es/es/booking/extras (you must first select a flight). When a button is clicked, I want the route to change to .../extras/bags and display a side navigation with ...

Improving the readability of Angular and RxJS code

I'm new to RxJs and angular and was wondering if there's a way to make the following code simpler while retaining its functionality. Is there room for improvement or is this as good as it gets? private configureDataStreams() { let params$ = thi ...

Is it possible for me to locally install @angular/[email protected] without needing to globally downgrade the latest @angular/[email protected] version?

Exploring My Angular Versions Currently, globally I have @angular/[email protected] installed as the latest version. However, for a specific project, I am interested in installing @angular/[email protected] locally without affecting the global v ...

Achieve a main-menu container with a full width dropdown using Bootstrap 4

I want the dropdown to start from the initial position for all menus and maintain a width of 600px. Even if I attempt to open the dropdown for "Main Menu 2" or "Main Menu 3" or "Main Menu 4", the dropdown should always start from the position of "Main Men ...

What type of module from commonjs is typically brought into a typescript document?

When importing a CommonJS module in a Typescript source, an object containing exported features of the module is received. In a specific use case, the declarations for NodeJS's fs module declare the exports as (typescript-) module, not as type. An in ...

The File Filter feature of Angular's ng2-file-upload is not functioning correctly for PNG files in the Internet Explorer

I am encountering an issue with the file uploader plugin ng2-file-upload when trying to upload a PNG file using Internet Explorer 11. For some reason, the PNG files are not being added to the queue, even though all other allowed file types work perfectly f ...

Can you point out the distinction?

I've been diving into Angular and Angular Material lately. I came across an example on the Angular Material website about creating a table. When I tried to replicate it exactly as shown, the styling seemed off. It looked like half of the CSS styles w ...

Typescript's return type can be autocompleted based on the input object provided

Update: Shoutout to for providing the completed version which can be accessed here: https://github.com/web-ridge/react-ridge-translations/blob/main/src/index.ts I've been developing a translation library for React / React Native, but I'm facing ...

How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met: 1. Only allow uploading of zip files; display an error message for other file types 2. Restrict the file s ...

Ways to verify the data type of a column in a table

I am currently working on making a table configurable. To achieve this, I am creating a demo component that will allow me to build my own customizable table. I intend to pass certain parameters to my table such as column names and data. The column names s ...

Encountering issues with addMethod functionality in TypeScript with the latest version of Yup

yup package Issue Encountering an error when adding a custom method to a yup instance using the addMethod function: TS2339: Property 'title' does not exist on type 'typeof import("node_modules/yup/lib/index")' Steps to rep ...

What is the method by which the Material-UI Button component determines the properties for the component that is passed to the `component` prop

Could someone please clarify how Material-UI enhances the properties of its Button component by incorporating the properties of a specific component if passed in the component attribute? interface MyLinkProps extends ButtonBaseProps { someRandomProp: str ...

Eslint highlighting the initial function declaration within a Vue script

I'm currently creating a Vue file using a Typescript script, and encountering an unusual Eslint "error." https://i.sstatic.net/UXv3A.png The issue arises on line 15 with this specific complaint: Parsing error: Unexpected token, expected "," Interes ...

Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown: export interface ProductsList { id: boolean nome: string qtde: number ...