How can the adapter pattern be implemented in Angular when dealing with an HTTP response containing an array of objects?

Using the adapter pattern in Angular, I have successfully adapted Http response to an 'Invoice' object. However, I am facing a challenge when one of the properties inside the 'Item' is an array.

In this scenario, the 'items' property in the 'Invoice' class is an array of 'Item'. How can I implement the adapter pattern to handle this situation?

export class Invoice {
    constructor(
        public id: number,
        public customerId: number,
        public customer: string,
        public date: string, 
        public finalAmount: number, 
        public items: Item[], 
    ) {}
}


export interface Adapter<T> {
    adapt(item: any): T;
}


@Injectable({
    providedIn: 'root'
})
export class InvoiceAdapter implements Adapter<Invoice> {
    adapt(item: any): Invoice {
        return new Invoice (
            item.id,
            item.customer.id,
            item.customer.name,
            item.date,
            item.final_amount.total,
            item.items // how to adapt to 'Item'?
        );
    }
}
export class Item {
    constructor(
        public id: number,
        public invoice: number,
        public productId: number,
        public product: string,
        public size: number,
        public quantity: number,
        public amount: number,
    ) {}
}

export class ItemAdapter implements Adapter<Item> {
    adapt(item: any): Item {
        return new Item (
            item.id,
            item.invoice,
            item.product.id,
            item.product.name,
            item.size,
            item.quantity,
            item.amount,
        );
    }
}

Answer №1

To streamline the process, you may choose to assemble an array of Items first before feeding them into your invoice constructor.

export class InvoiceAdapter implements Adapter<Invoice> {
    adapt(item: any): Invoice {
        let itemArray = item.items.map(item => {
            return new Item(item.id, item.invoice, etc ,etc)
        }
        return new Invoice (
            item.id,
            item.customer.id,
            item.customer.name,
            item.date,
            item.final_amount.total,
            itemArray
        );
    }
}

If utilizing an adapter is preferred.

export class InvoiceAdapter implements Adapter<Invoice> {
    adapt(item: any): Invoice {
        let itemArray = item.items.map(item => {
            return ItemAdapter.adapt(item)
        }
        return new Invoice (
            item.id,
            item.customer.id,
            item.customer.name,
            item.date,
            item.final_amount.total,
            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

I encountered an issue when trying to call a class in angular 2, receiving the error message "Supplied parameters do not match any

A new class named items-class.ts was successfully created: export class ItemsClass { constructor(public name:string, public desc:string, public stat:string){} } To implement this class in a component called app.component.ts: import { Component } fro ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

The modal stubbornly refuses to close

The main component responsible for initiating the process is /new-order. Upon clicking on the confirm button, a modal window appears. <div class="col-12"> <button type="button" class="btn btn-primary m-1" (click)=& ...

Typescript error: Object may be 'undefined' when using object literals

I am encountering an issue when trying to run the same code in my Typescript application that works fine in the browser console: [{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution. Here is my plugin implementation: index.ts i ...

Leveraging TypeScript unions within functions to handle and throw errors

As a newcomer to TypeScript, I've encountered an odd error that I need help with. I have various objects sending data to the server and receiving fresh data back of the same object type. These objects use a shared method for sending the data, so I ap ...

Utilizing history in React with Typescript: A step-by-step guide

I am currently working on a function that navigates to My Page upon clicking a button. However, I encountered an error when trying to implement it in Typescript instead of JavaScript. I am seeking assistance to resolve this issue. //Topbar.tsx function Top ...

Ways to avoid using a specific type in TypeScript

Imagine having a class that wraps around a value like this: class Data<T> { constructor(public val: T){} set(newVal: T) { this.val = newVal; } } const a = new Data('hello'); a.set('world'); // typeof a --> Primitiv ...

Issue with Angular 2 - Basic form validation no longer functioning

The Angular 2 application I've been working on includes a simple form with input fields and basic HTML validation. Here's an example: <form (onSubmit)="submit()"> <input type="email" /> <input type="submit" value="save" /> ...

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

Is it feasible to send a variable to angular.json in order to prevent repetitive code?

I'm searching for a strategy to efficiently pass data to the angular.json file, eliminating the need for redundant build configurations. To illustrate my point better, let's use an example. Currently, in my angular.json file under the configurati ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

What is the best way to implement a late-binding clone method in TypeScript classes?

Creating a simple Cloneable interface for all my data classes in JavaScript is a straightforward task. However, when it comes to typing it properly in TypeScript, things get a bit more complex. Currently, I am putting together a solution like this: class ...

Tips for invoking a function from one React component to another component

Currently, I am working on two components: one is Game and the other is PickWinner. The Game component serves as the parent component, from which I need to call the pickWinner function in the PickWinner component. Specifically, I want to trigger the startP ...

Tips for resolving package conflicts while integrating Wagmi View into a React/Typescript application

I am facing an issue while attempting to incorporate wagmi and viem packages into my project. Currently, my project utilizes the react-scripts package with the latest version being 5.0.1, and Typescript is operating on version 4.9.5. However, upon trying ...

Tips on launching a bootstrap modal by clicking a button in an Angular project

I'm working with a Bootstrap Modal that includes a button to trigger it. Here is the code: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data- ...

Explore an example of using custom controls in a FormArray within an Angular 5 reactive form on StackBlitz

Check out my sample project on stackblitz that tests nesting components and retrieving the complete form value. https://stackblitz.com/edit/mensand-hobbies-football-tennis This is a demonstration where I aim to utilize different components stored in an a ...

"Utilize React and Redux to fetch data from the server after making changes with an API

I am currently using a combination of react, redux, and typescript in my project. My goal is to add an item from the react component by making an API call and then displaying whether the operation was successful or not. To achieve this, I am fetching data ...