Angular automatically interprets strings as dates

Currently, I have numerous entities that have been defined:

export class Meeting implements IHasId {
    id = 0;
    locationId = 0;
    meetTime = new Date();
    isFinalized = false;
    imageId: number = null;
    description = '';
    name = '';
}

Alongside this, I utilize a generic crud service that is responsible for resolving these entities to their original type

export class ApiResourceBaseService<T extends IHasId> {
  get(id: number): Observable<T> {
    return this.http.get<T>(`${this.apiUrl}/${this.route}/${id}`);
  }
}

Although Typescript Generics are quite useful, there is an issue when I call get<T> as Typescript incorrectly assumes that my JSON data is accurate. This results in my date objects being resolved as strings instead of dates.

Given the multiple entities I have, it becomes tedious to create custom constructors/adapters to parse the dates.

Does anyone have a more efficient solution to automatically resolve dates?

Answer №1

My approach involves utilizing an interceptor for data transformation. While I plan to automate the generation of models and API resources from documentation in the future, I'm currently employing the following workaround:

export class ModelBinderInterceptor implements HttpInterceptor {

    // Regular expression for ISO 8601 Date.
    DATE_TIME_TIMEZONE_REGEXP =
    /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/;

    constructor() {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                event = event.clone({body: this.modifyBody(event.body)});
            }
            return event;
        }));

    }

    private modifyBody(body: any) {
        return this.deserializeDates(body);
    }

    private deserializeDates(obj) {
        if ((!(obj instanceof Object)) || (isString(obj))) {
            return obj;
        }

        for (const key of Object.keys(obj)) {
            const value = obj[key];
            let date;

            if (isString(value) &&  (this.DATE_TIME_TIMEZONE_REGEXP.test(value))) {
                date = new Date(value);
                // Check if the date parsing is successful
                if (isNaN(date.getTime())) {
                    return;
                }
                obj[key] = date;
            }
            this.deserializeDates(value);
        }

        return obj;
    }
}

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

Unit Testing AngularJS Configuration in TypeScript with Jasmine

I'm in the process of Unit Testing the configuration of a newly developed AngularJS component. Our application uses ui-router for handling routing. While we had no issues testing components written in plain Javascript, we are encountering difficulties ...

Typescript can represent both optional and required generic union types

Purpose My goal is to establish an optional parameter unless a specific type is provided, in which case the parameter becomes mandatory. Desired Outcome I aim for the get method below to default to having an optional parameter. However, if a type TT is p ...

Accessing the personal data fields of a MongoDB object

My current environment setup includes: NodeJS: 5.7.1 Mongo DB: 3.2.3 MongoDB (NodeJS Driver): 2.1.18 TypeScript: 1.8 I have defined an Object using Typescript as: class User { private _name:string; private _email:string; public get name():strin ...

Ways to manage multiple Observables

Two Observables are being returned from different services, each providing only one value (similar to Observable.just()). In TypeScript, types play a crucial role in this context. Is there a method to determine when both Observables have been resolved (in ...

Displaying sorted objects from Angular serviceIn Angular 8, let's retrieve an object

In my Angular8 application, I am running a query that fetches a data object. My goal is to sort this data object based on the order value and then display each product item on the browser. For example, here is an example of how the output should look like ...

What is the best way to view real-time updates on an Angular project?

Currently, I am working on an Angular project and typically use the command "ng serve" to run it. However, in comparison to Ionic where I can simply run "ionic serve" and view live updates of my code changes in the browser, I am wondering how I can achie ...

Ways to verify if JSON.parse fails or yields a falsy outcome

Objective: const jsonData = JSON.parse(this.description) ? JSON.parse(this.description) : null When executing the above statement, my aim is to have the ability to parse a value successfully and return null if parsing fails. However, instead of achieving ...

Creating Reactive Form Validators in Angular 5: Implementing a Custom Validator to Compare Two Form Controls

To ensure my save button is disabled only when validation fails, I have implemented the following logic: private createForm() { this.commentForm = new FormGroup({ 'startTime': new FormControl(this.startTime, [ this. ...

Conceal Columns in DevExtreme with Angular2 EditMode

Is there a way to conceal a DataGrid Column while in EditMode by utilizing DevExtreme and Angular2? <h3>Test</h3> <dx-data-grid id="gridContainer" [dataSource]="xxx" [allowColumnReordering]="true" [allowColumnResizing]="true" [rowAltern ...

The JSON data does not meet the requirements set by the JSON Schema and

Both the given JSON schema and JSON document are valid JSON formats. However, I am facing difficulty in generating a valid JSON document that adheres to the JSON schema. An error message is displayed: should NOT have additional properties JSON Schema { ...

Is it possible to send all API requests through the server side in an Angular Universal application?

I have integrated angular universal into my angular project and I am looking to ensure that all API requests, both post and get, are made from the server side rather than the client side. Is it possible to achieve this functionality in Angular? For exampl ...

Having trouble making ngMouseEnter (and other similar commands) function correctly

I'm currently working with Bootstrap 4 on Angular 6, and I have a delete button that I want to change its icon when the cursor hovers over it. I've tried using various ng functions like ngMouseOver and ngMouseUp, but none seem to be effective in ...

How to use jQuery to dynamically generate a JSON object within a loop

http://jsfiddle.net/hU89p/219/ This example demonstrates the creation of a JSON object based on selected checkboxes. When selecting one checkbox, the JSON would look like: var data={"name":"BlackBerry Bold 9650", "rating":"2/5", "Location":UK}; By sele ...

Displaying the count of items outside the Angular 2 ngFor loop

As a beginner in Angular, I've encountered a small issue. How can I display the actual number of items outside of an *ngFor loop? Currently, I'm using filter and pagination pipes in this manner: *ngFor="let item of items | filterBy: ['name ...

Typescript and the way it handles responses from REST APIs

Starting off, I must mention that I am relatively new to TypeScript, although I have been a JavaScript developer for quite some time. I am in the process of transitioning my existing JavaScript application to TypeScript. In the current JavaScript app, the ...

Converting information from JSON files (using tweepy) into a pandas data table

After streaming tweets from Tweepy and saving them as a text file, I am now interested in converting this data into a pandas dataframe. Despite searching through Stack Overflow and the pandas documentation, I still feel unsure about how to proceed with par ...

What is the best way to deactivate select option(s) based on the JSON data retrieved through AJAX?

I am facing an issue with a dropdown menu that contains several options. My goal is to loop through these options and set the disabled attribute on specific ones based on the result of an Ajax call. https://i.sstatic.net/9k3f9.png This is what I am tryin ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...