Utilizing an API to dynamically augment a JSON object with user input in Angular

Hello, I am working on adding an input value to an object property.

The scenario is that a customer wants to add an item to their shopping cart, but before adding the item, they need to choose the size. I have the form set up with validation and can retrieve the size value when a radio button is clicked and the onSubmit() function is called. The cart service function is already in place for adding items to the cart using an API, and I can retrieve the id of the posted item. Now, I need to get the Valuesize and add it as a property (size:Valuesize), which is a string.

I pass in Valuesize as a parameter to the cartservice. My challenge lies in updating the object property. I tried implementing this functionality, but it's not behaving as expected. Any guidance on how to proceed would be greatly appreciated.

Code snippet below:

Model

My model has 'size' as an optional property, so it doesn't exist on the object by default. I'm not sure if I should make a post request first, followed by a get request by id to add the property afterwards.

import { Product } from './product';

export class CartItem {
    static splice(arg0: number) {
        throw new Error('Method not implemented.');
    }

    id: number;
    productId: number;
    productName: string;
    qty: number;
    price: number;
    size?:string;
    imageUrl:string;

    constructor(id:number, size:string,  product:Product, qty=1) {
        this.id = id;
        this.productId = product.id;
        this.price = product.price;
        this.size = size;
        this.productName = product.name;
        this.qty = qty;
        this.imageUrl = product.imageUrl;    
    }
}

productlist.ts

// Component code here...

cartservice

// Service code here...

The JSON structure in db.json

"cart": [
    {
        "product": {
            "id": 4,
            "name": "Purple Outfit",
            "description": "Lorem Ipsum is simply dummy text...",        
            "imageUrl":"http://localhost:4200/assets/purpleoutfit4.png",
            "price": 100
        },
        "id": 7
    }
],

Answer №1

Attempting to utilize Object.assign does not align with my intentions as it merely copies enumerable own properties from one or more source objects to a target object, rendering it unsuitable for my requirements. The same issue arises with the put method, leading to unnecessary code clutter. I have streamlined the process by removing excessive code and starting fresh with:

addProductToCart(product:Product,Valuesize:string):Observable<any>{
    return this.http.post<any>(cartUrl, {product})
}

Any additional code necessary for adding Valuesize must be inserted before the return statement.

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

A guide to simulating Custom Dialog in Angular for Unit Testing with Jest

Currently, I am in the process of creating test cases for unit tests and ensuring code coverage for a method that triggers a dialog component when isEdit = 'true' which is retrieved from localStorage. The issue arises with the first test case wh ...

Creating connections between different services and components

I'm having an issue with importing my service into my component as it's giving me a "cannot find module" error. Below is the code from selectHotel.component.ts import { Component } from '@angular/core'; import { GetHotelService } from ...

What is the best way to divide two ranges that are intersecting?

Seeking a method to divide two overlapping ranges when they intersect. This is my current progress using typescript, type Range = { start: number; end: number; }; function splitOverlap(a: Range, b: Range): Range[][] { let result = []; const inters ...

transmit information to a service using Angular 8

There are 4 multiselect dropdowns, and when I click on an event, I save the data array of objects in the same component. Now, I need to send this data to display it in another component. To achieve this, I am using a service. However, every time I send th ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Using Partial function input in TypeScript

I am in need of a function that can accept partial input. The function includes a variable called style, which should only have values of outline or fill, like so: export type TrafficSignalStyle = 'outline' | 'fill' let style: TrafficSi ...

What is the best way to organize information within a template using a *ngFor loop without needing to include functions directly in the template?

When working with Angular 11, I encountered a scenario where a Component receives an array of data from an external source that needs to be displayed in a template using a *ngFor loop with custom formatting. While my initial approach involved creating func ...

Is it possible to reuse a variable within a single HTML tag when using Angular 2?

I encountered a strange issue with Angular 2 that may be a bug. I noticed that I couldn't print the same variable in a template twice within the same HTML tag. When I tried to use the following code, it resulted in error messages. <div class=" ...

Ways to retrieve multiple values from the backend using observables

I am offering a service that connects to the backend. After making a request, I expect to receive two values, x1 and x2. How can I modify my code to handle this? Code: public startWebService(fieldGeometry) { var endpointURL = this.buildEndpointURLForLIDA ...

Discover the contents of an Object's key in TypeScript

I currently have a variable of type object. let ref_schema_data: object The value of ref_schema_data: { '$schema': 'http://json-schema.org/draft-07/schema', '$id': 'tc_io_schema_top.json', allOf: [ { type: &a ...

Adding classes dynamically in Angular 2 app functionality

With this particular layout in mind: <li role="menu" class="drop-down"> <a class="drop-down--toggle"> <span class="flag-icon" [class]="_current.flag"//<-- don't work></span> </a> <ul class="drop-down--men ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

Unresolved peer dependencies in Angular 2

I recently set up an angular2 project using CLI, and my package.json file is structured as shown below: { "name": "thesis-proto", "version": "0.0.0", "license": "MIT", "angular-cli": {}, "scripts": { "ng": "ng", "start": "ng serve", ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

Tips for eliminating a port from an Angular 2 URL

Whenever I launch an angular2 project, it automatically includes localhost:4200 in the URL, even after deploying it on a server. Is there a way to remove the port number from the URL without making changes to the core files? I attempted to modify the pac ...

Assign a class to the following element using an Angular 2 Directive

I have a dropdown menu and I want to incorporate an Angular2 directive to control the opening and closing of this dropdown. How can I apply the open class to the latest-notification div, knowing that my directive is applied to the button tag? Below is my ...

TypeScript Generic Functions and Type Literals

Everything seems to be running smoothly: type fun = (uid: string) => string const abc: fun = value => value const efg = (callback:fun, value:string) =>callback(value) console.log(efg(abc, "123")) However, when we try to make it generic, we e ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...