Angular efficient approach to changing object properties

When working on creating or updating records, I encounter a problem with the length and cleanliness of my code. The dealTypeValues object varies based on the dealDispositionType (buyout or sale), resulting in lengthy and messy code.

Does anyone have suggestions on how to streamline the code to minimize the payload or declaration of dealTtype values object? Or perhaps a cleaner implementation method for the code below, which contains multiple payload objects. Thank you.

#html code

<ng-template #editButtons>
        <div class="flex" *ngIf="isEditing">
          <app-page-section-cards-btn
            [btnData]="pageSectionsOptions.btnData.cancel"
            (btnClickEvent)="cancelEdit()"></app-page-section-cards-btn>
          <app-page-section-cards-btn
            [btnData]="pageSectionsOptions.btnData.save"
            (btnClickEvent)="saveDeal()">
        </app-page-section-cards-btn>
        </div>
      </ng-template>

#ts code

saveDeal(){
    if(!this.isExistingDeal){
      if(this.dealDispositionFormFields.dealDispositionType === 'Buyout') {
        const dealTypeValues = {
          "id": 0,
          "name": this.dealDispositionFormFields.dealName,
          "summary": this.dealDispositionFormFields.summary,
          "terminationPayment": this.dealDispositionFormFields.terminationPayment,
          "effectiveDate": AppUtils.convertDateStringToYYYYMMDD(this.dealDispositionFormFields.effectiveDate),
          "totalBrokerCommission": this.dealDispositionFormFields.totalBrokerCommission,
          "dealId:": 0,
        } 

        const payload = {
          "id": 0,
          "name": this.dealDispositionFormFields.dealName,
          "dealType": "Idle Buyout",
          "annualRentProposed": null,
          "annualRentCurrent": null,
          "firmTermRemaining": null,
          "firmTermAdded": null,
          "maxAvailableTerm": null,
          "status": null,
          "capitalContribution": null,
          "parentCloneId": null,
          "accountId": this.currentAccount.accountId,
          "transactionId": this.transactionData.id,
          "dealTypeValues": JSON.stringify(dealTypeValues)
        }

        this.createDispositionDeal(payload);
      }else if(this.dealDispositionFormFields.dealDispositionType === 'Sale') {
        const dealTypeValues = {
          "id": 0,
          "name": this.dealDispositionFormFields.dealName,
          &quo...
        
    }
    
   }
    createDispositionDeal(payload:any) {
      this._dealService.createDeal(payload)
      .subscribe(
        res=>{
          this._notificationService.showSuccess('Deal was successfully created.');
          this.gotoManageDealsEvent.emit('');
        },
        err=>{
          console.log('Error creating deal')
        }
      )
    }
    updateDispositionDeal(payload:any) {
      this._dealService.updateDeal(payload)
      .subscribe(
        res=>{
          this._notificationService.showSuccess('Deal was successfully updated.');
          this.gotoManageDealsEvent.emit('');
        },
        err=>{
          console.log('Error creating deal')
        }
      )
    }
  }

Answer №1

Utilizing TypeScript's Object destructuring and Spread Syntax

Develop a modal for DispositionalDeal. Modify property types according to your requirements.

export interface DispositionalDeal {
  id: number;
  name: string;
  dealType: string;
  annualRentProposed: number;
  annualRentCurrent: number;
  firmTermRemaining: number;
  firmTermAdded: number;
  maxAvailableTerm: number;
  status: string;
  capitalContribution: number;
  parentCloneId: number;
  accountId: number;
  transactionId: string;
  dealTypeValues: any;
}

Create a getter for payload (Default values will be based on Buyout createDispositionDeal)

  get buyOutDealTypeValues(): any {
    const {
      dealName,
      summary,
      terminationPayment,
      effectiveDate,
      totalBrokerCommission,
    } = this.dealDispositionFormFields;
    return {
      id: 0,
      name: dealName,
      summary,
      terminationPayment,
      effectiveDate: AppUtils.convertDateStringToYYYYMMDD(effectiveDate),
      totalBrokerCommission,
      dealId: 0,
    };
  }

  get payload(): DispositionalDeal {
    return {
      id: 0,
      name: this.dealDispositionFormFields.dealName,
      dealType: 'Idle Buyout',
      annualRentProposed: null,
      annualRentCurrent: null,
      firmTermRemaining: null,
      firmTermAdded: null,
      maxAvailableTerm: null,
      status: null,
      capitalContribution: null,
      parentCloneId: null,
      accountId: this.currentAccount.accountId,
      transactionId: this.transactionData.id,
      dealTypeValues: this.buyOutDealTypeValues,
    };
  }

Getter for Sales DealTypeValues

  get salesDealTypeValues(): any {
    const {
      dealName,
      salePrice,
      brokerCommission,
      transactionCosts,
      earnestMoneyDeposit,
      inspectionPeriod,
      estimatedClosingDate,
      netBookValue,
    } = this.dealDispositionFormFields;
    return {
      id: 0,
      name: dealName,
      salePrice,
      brokerCommission,
      transactionCosts,
      earnestMoneyDeposit,
      inspectionPeriod,
      estimatedClosingDate: AppUtils.convertDateStringToYYYYMMDD(estimatedClosingDate),
      netBookValue,
      dealId: 0,
    };
  }

Therefore, saveDeal() will be as follows

  saveDeal() {
    const { dealDispositionType } = this.dealDispositionFormFields;

    let request = {};

    if (!this.isExistingDeal) {
      if (dealDispositionType === 'Buyout') {
        request = this.payload; // Since payload is in line with Buyout creation, no further manipulation is needed
      } else if (dealDispositionType === 'Sale') {
        request = {
          ...this.payload,
          dealTypeValues: this.salesDealTypeValues,
          dealType: 'Idle Sale',
        };
      }

      this.createDispositionDeal(JSON.stringify(request));
    } else {
      const { dealTypeValues, id, status } = this.dealData;
      if (dealDispositionType === 'Buyout') {
        const dealType = {
          ...this.buyOutDealTypeValues,
          id: dealTypeValues.id,
          dealId: dealTypeValues.dealId,
        };

        request = {
          ...this.payload,
          dealTypeValues: dealType,
          id,
          status,
        };
      } else if (dealDispositionType === 'Sale') {
        const dealType = {
          ...this.salesDealTypeValues,
          id: dealTypeValues.id,
          dealId: dealTypeValues.dealId,
          summary: this.dealDispositionFormFields.summary,
        };

        request = {
          ...this.payload,
          dealTypeValues: dealType,
          dealType: 'Idle Sale',
          id,
          status,
        };
      }

      this.updateDispositionDeal(JSON.stringify(request));
    }
  }

If there are any parts that you didn't grasp, feel free to let me know.

Full Example Code

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

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

Updating the color of specific buttons using ngFor in Typescript and Angular 8

I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span> or a <button>. Now, ...

Issue with Progressive Web App functionality when using Angular Pre Rendering

Currently, I am working on an Angular 10 Universal project. Whenever I execute the following command: "build:ssr": "ng build --prod && ng run PROJECT:server:production && node dist/PROJECT/server/main.js", I can see th ...

Problem with file organizer in Angular application - unable to see files and directories

I successfully integrated a file manager component following this tutorial. Despite no errors in vscode or chrome debug tool, my folders are not visible. Can anyone help me troubleshoot this issue? https://i.stack.imgur.com/ihEak.png I am unsure how to r ...

An exploration of navigating through a generic interface in Angular

I've recently started exploring Angular and I'm trying to incorporate a generic interface to reuse pagination models from different sources. Let me share some code examples to clarify. export interface IUser{ id: string; name: string; email: stri ...

Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties: albumId: 1 id: 1 thumbnailUrl: "https://via.placeholder.com/150/92c952" title: "accusamus beatae ad facilis cum similique qui sunt" url: "https://via.placeh ...

Issue encountered with Typescript and Mongoose while operating within a Kubernetes cluster environment with Skaffold configuration

Here is the code snippet, const userSchema = new mongoose.Schema({ email: { type: String, required: true, }, password: { type: String, required: true, }, }); console.log(userSchema); userSchema.statics.build = (user: UserAttrs) =& ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Creating an SCSS class in a component that is customizable and can

After doing some research and reading various guides and blogs, I am still struggling to find the right solution for this issue. Imagine having the following classes in your main styles.scss file: .btn { padding: 5px; text-transform: uppercase; } .b ...

The Kendo-datepicker always excludes the number zero in the day section

When I try to enter the date: 5/01/2017 The first zero in the days section is always missing when using kendo-date-picker, resulting in the following date: 5/12/17 In my HTML code: <kendo-datepicker [min]="min" [max] ...

Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates? var x = { "12": [3, 4], "13": [3], "14": [1, 4] }; The resulting array should only contain unique values: [1, 3, 4]; ...

Update a BehaviourSubject's value using an Observable

Exploring options for improving this code: This is currently how I handle the observable data: this.observable$.pipe(take(1)).subscribe((observableValue) => { this.behaviourSubject$.next(observableValue); }); When I say improve, I mean finding a wa ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

I am puzzled as to why I keep receiving the error message "Cannot read property 'poPanel' of undefined"

CSS In my project, I am implementing a feature that displays an ordered list by looping through an array of objects and adding them on a button click. It works smoothly for adding items, but when I try to implement a remove function to delete each item, I ...

Having trouble uploading SharePoint list item with attachment from Angular to ASP.NET Core Web API via NgModel

Recently, I successfully added a SharePoint list item with an attachment from Angular to ASP.NET Core Web API. This was achieved using FormControl in the Angular application. I found guidance on how to upload files from Angular to ASP.NET Core Web API at ...

The Capacitor Community Electron Platform, which combines IONIC, Angular, and Electron, encountered a TypeError: [ERR_INVALID_ARG_TYPE]. This error message indicates that the "path" argument must be in the

I have been attempting to follow the guidelines provided on to integrate the Capacitor Community Electron into a brand new Ionic Angular Test App. Everything is going smoothly until I reach the step where I need to add the platform as per the instructions ...

How can you create an interface where the value type is determined by the key, but not all keys are predefined?

Below is an illustration of a data structure that I aim to define as a type in TypeScript: const dataExample = { Folder: { "Filename.js": { lines: { total: 100, covered: 80, ...

Unable to upload file in angular2 due to empty Body (FormData)

Attempting to upload a photo with Angular2 to my REST Service (Loopback). The Loopback service has been successfully tested using Postman and is able to accept files with the x-www-form-urlencoded header. Below is a simplified version of the service metho ...

What is the necessity of Node Js for Angular and how does Angular Cli play a pivotal role?

As a newcomer to the world of Angular technology, I stumbled upon this intriguing query. What is the role of Node.js in Angular? After all, isn't Node.js primarily a backend technology? ...