Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format.

Currently, my code snippet where this.products = product simply saves the array along with the list of products.

//Data retrieved from the API

[ {datetime: "2017-06-25T07:45:00+08:00", name: "Apple", unit: 1, product: [{eating_time: "2017-06-25T07:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T17:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T23:55:00+08:00", qtytaken: 1, chart_bar=1 } ] 
]

// Product Class

class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor({eating_time, qtytaken, chart_bar })  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        this.products = product ;
        }
}

Answer №1

Implementing interface or class with no constructor and utilizing the map function

export interface ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

}

Your implementation should include the map function

return this.http.get(...)
      .map(res => <ProductTaken>res.json())

SEE LIVE DEMO

Answer №2

While I've managed to come up with a solution, I'm curious to know if there's a more efficient approach than utilizing forEach.

class Item {
    consumptionTime: Date;
    quantityTaken: number;
    barCode = 1;

    constructor(consumptionTime, quantityTaken, barCode )  {
            this.consumptionTime= new Date(consumptionTime);
            this.quantityTaken = dosage;
            this.barCode = barCode;
    }
}

export class ConsumableItem {
    dateTime: Date;
    name: string;
    unit: number;
    items: Item[];

    constructor({dateTime, name, unit, item} )  {
        this.dateTime = new Date(dateTime) ;
        this.name = name;
        this.unit = unit;
        let itemArray = [];
        item.forEach(function(element) {
          itemArray.push(new Item(element.consumptionTime, element.quantityTaken, element.barCode));
        this.items = itemArray ;
        }
}

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

Tips for Implementing Error Handling in Angular using Sweetalert2

On this code snippet, I have implemented a delete confirmation popup and now I am looking to incorporate error handling in case the data is not deleted successfully. confirmPopUp(){ Swal.fire({ title: 'Are You Sure?', text: 'Deleti ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

Using Systemjs with Angular 2 results in 50 server calls for loading resources

While following the Angular2 quickstart tutorial on Angular.io, I noticed that it was making 50 separate requests, which left me wondering why. Is there a way to consolidate all these requests into one? My goal is to have a maximum of 8 bundles. This is ...

FirebaseJS 4.0 is not compatible with projects created using Angular CLI

Having trouble integrating firebasejs 4.0 into my Angular CLI project. Here are the steps I followed: ng new firebasetest cd firebasetest ng serve ==> works fine After adding this line to index.html: <script src="https://www.gstatic.com/firebasej ...

Security concern regarding XSRF in Spring and Angular 5

For my current project, I am using Spring as the backend (generated with microservices with Jhipster) and Angular5 as the frontend. On the server side, CSRF security is added (it was enabled by default when we created microservices with Jhipster). Workin ...

Posting data from an Angular 2 frontend to an Express server: A step-by-step

Seeking guidance as a beginner trying to understand the process of sending contact form data from Angular 2 to a Node/Express server. Currently, I have Angular 2 hosted on localhost:4200 and the express server running on localhost:3000. However, when attem ...

What is included in the final Angular build package selection?

Is there a tool available to track packages included in the final build of an Angular project? For instance: I am using the package "@angular/compiler" as a dependency in my package.json, but it is not a dev dependency. According to the Angular ...

Vue.js - A dynamic parent component generates content based on data passed from a renderless child component

I am currently working on developing a system for generating buttons using vue 3 and vue-class-component. The main goal is to create a flexible button generation process, where the number of buttons generated can vary (it could be just one or multiple). Us ...

Display a dynamic array within an Angular2 view

I have a dynamic array that I need to display in the view of a component whenever items are added or removed from it. The array is displayed using the ngOnInit() method in my App Component (ts): import { Component, OnInit } from '@angular/core' ...

Working with Angular2: Linking dropdown values with any number of items

Is there a way to dynamically bind drop down values with numbers from 1 to 100 using a loop in Angular2? I am currently using Ngprime dropdown for a limited number of values, but how can I achieve this for any number of values? Here is the template: < ...

What is the best way to rid ourselves of unwanted values?

In the laravel-vue-boilerplate package, there is a User CRUD feature. I duplicated this functionality to create an Item CRUD by making some changes and adjustments. Everything is working fine except for one issue: after editing an item, when trying to add ...

Accessing enum values in a view with Typescript and AngularJS version 1.5

Recently started working with Angular 1.5 and Typescript I have a service that returns data in an array format called devices.headerEntries: [{name:id,value:45} ,{name:Mode,value:1},{name:State,value:2},{name:serialnum,value:123434} I created a componen ...

The ng build run command is encountering an issue due to the absence of Angular.json file

I attempted to update Angular CLI but encountered a major issue. Here is the Error Image. Can someone please provide guidance on how to resolve this problem? @angular-devkit/core 0.5.6 @angular-devkit/schematics 0.5.6 @angular/cli ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

Guide to retrieving Response Header in Angular 8 when making a POST request

Looking to fetch the response Header in Angular 8 after a post request and securely store the jwt token in localstorage? login(req): Observable<any> { return this.http.post(this.apiUrl + '/login', req).pipe( map(res => { if ...

Sharing assets across different Angular applications is a powerful way to improve code

I am currently developing a series of small applications that will utilize common modules and shared assets. For guidance on how to structure the projects, refer to this answer: The organization of my project folders is as follows: -root --projects ---ap ...

Using TypeScript's conditional types for assigning types in React

I'm tasked with creating a component that can belong to two different types. Let's call them Type A = { a: SomeCustomType } Type B = { b: SomeOtherDifferentType } Based on my understanding, I can define the type of this component as function C ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

In the process of using SWRInfinite for React Infinite Scrolling, the initial call may be made

Can someone help me understand why my useGetItems hook, which imports the usePagination hook, keeps repeating the first call history every time I scroll? /items?_page=1&_limit=40 /items?_page=1&_limit=40 /items?_page=2&_limit=40 /items?_page=1 ...

Customize TypeScript Generic Types in Method<T> Extending from a Base Class<T> as a Backup Plan

In my example, I have created an Angular Service with multiple Generic Types that can be overridden through the methods. The issue I am encountering revolves around = versus extends and how it affects typing in the arguments. Strangely, using = works perfe ...