Modify the name of the variable when sending the object to an HTTP service in Angular version 6

    export class ShopModel {
    public id: number;
    public name: string;
    public email: string;
    public phone: string;
    public website: string;
    public address: string;
    public gst_number: string;
    public pan_number: string;
    public tan_number: string;
    public plan_id: number;
    public status: number = 1;
    public users: UserModel[];
    public customers: CustomerModel[];
    public categories: CategoryModel[];
    public plan: PlanModel;

    public static getDummyModel(): ShopModel {
        return new ShopModel();
    }
}

This represents my Data model with various properties and associations.

{
    "shop": {
        "name": "Develop Shop",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16657e79252225226656727360737a7966387465">[email protected]</a>",
        "phone": "2343",
        "website": "dtewrtyty",
        "address": "rgtyyiuyouyip",
        "gst_number": "eytyw",
        "pan_number": "rywtywe",
        "tan_number": "ryeyru",
        "plan_id":1,
        "users_attributes": [{
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73001b1c0333171605161f1c035d1100">[email protected]</a>",
            "role": "user"
        }, {
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5968d8a95d7a581809380898a95cb8796">[email protected]</a>",
            "role": "staff"
        }]
    }
}

I am looking to send this JSON object via an HTTP POST request to the server.

To achieve this, I need to modify the users array in the data object to users_attributes before sending it.

If you have any suggestions on how best to achieve this using Angular 6, please advise me accordingly. Thank you!

Answer №1

If you're looking for a solution, here's an example that could help with the task (using lodash).

let storeModel = StoreModel.getSampleModel();
let storeObject = {
  "name": storeModel.name,
  "email": storeModel.email
}

storeObject['users_attributes'] = [];

_.forEach(storeModel.users, user => storeObject.users_attributes.push({'email': user.email, 'role': user.role}));

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

Angular 2 approach to retrieving items from an Observable<Xyz[]>

After reviewing the Typescript code in an Angular 2 service: getLanguages () { return this.http.get(this._languagesUrl) .map(res => <Language[]> res.json().data) .catch(this.handleError); I'm encountering a challenge whe ...

Unable to serve static files when using NextJs in conjunction with Storybook

The documentation for Next.js (found here) suggests placing image file paths under the public directory. I have a component that successfully displays an image in my Next.js project, but it doesn't render properly within Storybook. The image file is ...

Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge... The products.ts file contains the ActionCreators and Reducers for Products... import { setStock } from './Store.ts'; //.... export const addProduct = (product: IProduct) ...

Having trouble getting tsserver-plugins to function properly in either Atom or VSC

My team and I are on a mission to enhance our Angular 2 templates with code completion, similar to what is showcased in this gif. To achieve this goal, we require: tsserver-plugins coupled with tslint-language-service and @angular/language-service We ...

Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test"> <mat-radio-button *ngFor="let option of options | filter:searchText" class="cssForRow" [value]="option" ...

Angular Error TS2554: Received x arguments instead of the expected 0 on piped operators

I encountered an issue with Error TS2554: Expected 0 arguments, but got 4 when dealing with the observable getHappyDays(). The getHappyDays() Observable returns either Observable<HttpResponse<IHappyDays>> or Observable<HttpErrorResponse> ...

Handling exception type in child_process exec method - NodeJS with Typescript integration

Check out this sample code: const execPromise = util.promisify(exec); try { const { stdout } = await execPromise(cliCommand); } catch (error) { if (error instanceof S3ServiceException) { // error message is not handled correctly console ...

Utilizing Angular's async pipe to dynamically customize and assign values to variables

I have a parent component named A with over 20 child components, all of which extend A and are located within <ng-content></ng-content>. Within component A, I am updating the value of the showContent variable in multiple places. The issue aris ...

Automatic type inference for functions in TypeScript with arguments

I am looking to define an interface with the following structure: interface CheckNActSetup<D, C> { defs: (event: Event) => D, context: (defs: D) => C; exec: (context: C) => any[]; when: ((context: C) => boolean)[]; } and implement it usi ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

Issue with Typescript - Node.js + Ionic mobile app's Angular AoT build has encountered an error

Currently, I am in the process of developing an Android application using Node.js and Ionic framework. The app is designed to display random text and images stored in separate arrays. While testing the app on Chrome, everything works perfectly fine. Upon ...

What is the reason behind the ability to reassign an incompatible function to another in TypeScript?

I discovered this question while using the following guide: https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#types-of-arguments. Here is an example snippet of code: /** Type Heirarchy */ interface Point2D { x: number; y: ...

Setting the default value for Angular Material's select component (mat-select)

Many inquiries are focused on setting a default value to display in a "Select" control. In this particular case regarding Angular 8 template driven forms, the issue lies in the inability to show the default value in the mat-select when the button is clicke ...

A class definition showcasing an abstract class with a restricted constructor access

Within my codebase, there is a simple function that checks if an object is an instance of a specific class. The function takes both the object and the class as arguments. To better illustrate the issue, here is a simplified example without delving into th ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

Experiencing Typescript errors solely when running on GitHub Actions

I've been working on a React+Vite project with the Dockerfile below. Everything runs smoothly when I execute it locally, but I encounter errors like Cannot find module '@/components/ui/Button' or its corresponding type declarations and error ...

Strategies for effectively choosing this specific entity from the repository

Is it possible to choose the right entity when crafting a repository method using typeorm? I'm facing an issue where I need to select the password property specifically from the Admin entity, however, the "this" keyword selects the Repository instead ...

MQTT Broker specialized in Typescript

I'm looking to create a MQTT Broker using TypeScript and Angular. I've attempted a few examples, but I keep encountering the following error: Uncaught TypeError: http.createServer is not a function Here's a simple example of what I'm c ...

Transform the data prior to sending it back as an observable

I am fairly new to Angular 2 and the idea of Observables. However, what I am trying to accomplish should be quite simple for experienced experts :) Here's the situation: I have a component where I have subscribed to an observable coming from a servic ...

Tips for defining a data structure that captures the type of keys and values associated with an object

Is there a way for the compiler to verify the type of value in this scenario? type SomeType = { foo: string[]; bar: number | null; }; type SomeTypeChanges<K extends keyof SomeType = keyof SomeType> = { key: K; value: SomeType[K] }; declare ...