How to correctly deserialize dates in Angular 5

When working with Angular 5, I have encountered an issue where JSON data from an API is not properly deserialized into dates within an array. My model includes a definition like this:

    export interface ProcessDefinition {
    _id?: string;  
    processDefinitionName: string;
    myDates: Date[];
}

To fetch data from the API, I use HttpClient in a service class that returns an observable:

    public getItems(): Observable<ProcessDefinition[]> {
    let url = this.apiUrl + this.entityName + '/';

    this.loggerService.log(`Getting items with observable via http.`);
    this.loggerService.log(`URL: ` + url);

    return this.httpClient.get<ProcessDefinition[]>(url);
}

In my component, I call this service method as follows:

public loadProcessDefinitionData(): void {
    this.processDefinitionService.getItems().subscribe(items => {

        this.processDefinitions = items;

        // Various attempts to convert dates
        this.currentProcessDefinition = this.processDefinitions[0] || null;

        this.currentProcessDefinition.day1dates.forEach(dat => dat = new Date(dat));

        console.log(JSON.stringify(this.currentProcessDefinition.day1dates[0].getMonth()));

    });
}

Despite trying different approaches, I have been unable to successfully convert the dates into real dates using the 'new Date' approach suggested in similar discussions. I am seeking assistance to ensure that the dates in the ProcessDefinition[] observable are genuine, allowing me to perform operations like calling getMonth() on them.

If possible, I would like to handle this date conversion logic within the service to keep it consolidated in one place.

Thank you

Answer №1

Instead of utilizing the forEach method, consider using the array's .map function like this:

this.currentProcessDefinition.day1dates = this.currentProcessDefinition.day1dates.map(dat => new Date(dat))

If you prefer handling this in your service, you can implement it as follows:

  import { map } from 'rxjs/operators'

  getItems() {
    let url = this.apiUrl + this.entityName + '/';

    return this.http.get(url).pipe(
      // Mapping through each item in res and formatting the object
      map((res) => res.map(item => this.formatDates(item)))
    )
  }

  formatDates(results) {
    // Mapping through each date and replacing with Date objects
    results.day1dates = results.day1dates.map(dat => new Date(dat));
   return results;
  }

This code uses the Observable's own .map function within the pipe to transform the results. You can then subscribe to these transformations in your components as usual.

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

"Experience the ngx-youtube-player Angular component that allows for easy toggling between play and

My goal with ngx-youtube-player is to create a transparent div on top of it that toggles between playing and pausing the video when clicked. I am implementing this because my Angular project consists of numerous components, and one method of navigation is ...

Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below: Current Object: displayConfiguration: { widgetList: { widgetName: 'widget title', entityType: 'As ...

Secure authentication for Windows and an Angular 4 web application

Currently, I am working on an Angular 4 project that requires retrieving data from an Asp.Net WebApi. The WebAPI is set up with windows authentication and I am looking for a way to pass the user's windows identity from my Angular Application to the We ...

Deactivate user session in LoopBack 4 API

Can anyone provide a clear example of an API endpoint for logging out that allows for deleting the token stored during login instead of relying on the web browser? It seems there is no documentation available on how LoopBack generates a default user when ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Dynamic Angular API request

Attempting to retrieve data from multiple APIs obtained from an initial API call. loadData() { this.http.get(this.firstApi).pipe( .map(response => response.ip) ) .subscribe(ip => { console.log(ip); Observable.for ...

Extract Method Parameter Types in Typescript from a Generic Function

Can we retrieve the type of parameters of methods from a generic interface? For instance, if we have: interface Keys { create: any; ... } type MethodNames<T> = { [P in keyof Keys]: keyof T; } Then, is it feasible to obtain the type of paramete ...

Enhance filtering capabilities in FormGroup with an autocomplete input feature for more options

Seeking to implement a basic autocomplete textbox that allows selection from a filtered list of objects displayed by name. For instance, with an array of Country objects containing properties like countryName, countryCode, and countryId, the goal is to fi ...

Display the date format based on the computer's settings using Angular 2

When I visited http://momentjs.com/docs/#/displaying/format/, I noticed the "Localized formats" options like L. I thought that these settings would change the date display from mm/dd/yyyy to dd/mm/yyyy based on the user's browser or computer locale s ...

Using Typescript with Material UI Select

I have implemented a dropdown menu using Material UI select labeled "Search By." When the menu is clicked, it displays a list of options. I aim to store the selected option and update the label "Search By" with the chosen option. export default function U ...

Regex for US zip code with an optional format

Searching for a regular expression to validate US zip codes. I have come across multiple examples, but none of them cater to the scenario where the zip code is optional. The input field I am working on does not require a zip code, so it should accept a 5 ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

Is it possible to utilize the OnBlur prop based on a certain condition?

To display a component when the input is focused, follow the steps below: Click here for not focused state When you click on the text input, the component should appear like this: Click here for focused state The code snippet provided works correctly. ...

Encountered difficulties when attempting to install Angular Universal in my angular13 application

I'm facing some challenges while trying to incorporate @nguniversal/ into my angular 13 application. Are there any experts who can offer assistance? Angular CLI: 13.0.4 Node: 16.13.1 Package Manager: npm 8.1.2 npm ERR! code ERESOLVE npm ERR! ERESO ...

Angular 2 - Ensuring mandatory fields are completed when checkbox is checked

Hey everyone, I'm a newcomer to Angular2 and JS frameworks in general. I've been following tutorials on the official site but I can't seem to find a solution to my problem. So, I have a checkbox that is optional, but if it is checked, a new ...

Tips for combining Angular 2 with a current J2EE Spring project and deploying them on the same PORT

I currently have a project with Spring on the back-end and AngularJS 1 on the front-end. When I start the Spring server, it only opens one port for me: 8080 which allows me to access REST APIs and the AngularJS front-end components. https://i.stack.imgur. ...

Can TypeScript support passing named rest arguments within the type declaration?

Using Tuple types in TypeScript enables us to create typesafe rest arguments: type Params = [string,number,string] const fn = (...args: Params) => null // Type is (args_0: string, args_1: number, args_2: string) => null Is there a method to assign ...

Tips for adjusting the position of overflowing text on a website using CSS in real-time

I'm currently working on an Angular application and I'd like to customize the styling so that any text exceeding 128 characters is not displayed. Ideally, if the text exceeds 128 characters, it should move to the left; otherwise, it should remain ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...