Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a user clicks on the Buy button, an order should be placed. The challenge lies in binding the data to the property (prodID) but encountering difficulties in assigning the variable prodID within the array body[ ]. This limitation prevents the successful placement of orders using JSON since the prodID assignment is not functioning as intended.

An example snippet of the code is provided below:

import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { Woocommerce } from './Woocommerce';

// Remaining TypeScript component code...

The HTML template file app.component.html contains the structure for displaying the WooCommerce products and handling the buy functionality through buttons:

<h1>Woocommerce</h1>
<form>
  <table class="table table-hover">
    <thead class="thead-dark">
      <!-- Table headers omitted for brevity -->
    </thead>
    <tbody>
      <tr *ngFor="let r of result" [attr.id]="r.id">
        <td >{{r.id}}</td>
        <td>{{r.name}}</td>
        <td>{{r.price}}</td>
        <span *ngFor="let k of r.images">
          <td><img height="100" width="100" src={{k.src}}></td>
        </span>
        <td><button type="button" [attr.id]="r.id" class="btn btn-primary" (click)="buyNow(r.id)">Buy now</button></td>
      </tr>
    </tbody>
  </table>

Answer №1

For your specific scenario, creating a copy of the initial state for the body variable will always result in undefined.

Here is a solution to rectify this issue:

getBody(){
    return {
        payment_method: 'paypal',
        payment_method_title: 'Direct Bank Transfer',
        set_paid: true,
        line_items: [
            {
                product_id: this.prodID,
                quantity: 1
            }
        ]
    };
}

buyNow(getID: any) {
    this.prodID = getID;
    this.http.post<Woocommerce>(`${this.baseURL}/orders?consumer_key=${this.consumer_key}&consumer_secret=${this.consumer_secret}`, this.getBody(), {
        headers: new HttpHeaders().set('Content-Type', 'application/json' ),
      }
    ).subscribe(resp => {console.log(resp);});
}

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

Navigating the world of updating problems with Express.js

Currently, I am working on a MEAN stack project and facing challenges with the routing for updating. Saving operations are functioning correctly. In my Angular controller, I have defined the following scope method in which staff represents the object subm ...

Attempt the HTTP request again only for specific status codes

When developing my Angular application, I encountered a situation where I needed to make an HTTP call to a backend server. To enhance its reliability, I decided to incorporate an interceptor to implement the retry pattern. In the past, I utilized RxJS&apo ...

Encountering a TypeScript error when attempting to utilize indexOf on a Typed Array, leading to restriction

I have been working with an Interface, where I created an array of type Interface. I am currently facing some IDE error complaints when trying to use the .indexOf method on the Array. These errors seem confusing to me, and I'm hoping someone here migh ...

Arrange the keys of a map in ascending order, prioritizing special characters and their precedence

JavaScript ES6 Map Example: const map = new Map(); map.set('first', ['1', '2']); map.set('second', ['abc', 'def']); map.set('_third', []); map.set(')(*', []); map.set('he ...

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...

IdentityServer4: The authentication time is not specified

I'm currently working on an angular (asp.net core) application that utilizes an identityserver4 server for authentication. Initially, the login process works seamlessly, displaying the login form and returning both the id_token and access_token. How ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

Click to stay in the background

I am currently facing an issue where opening a new tab on click redirects the focus to the child window instead of staying in the current window. I would like the popup to open without blocking and allowing me to maintain focus on my current window. The c ...

Retrieve information from an HTML form

Currently, I have a piece of Javascript that fetches the HTML for a form from the server using an XMLHttpRequest and then displays the form on the page. I am looking for a solution to extract the data that would be sent via POST if the form were submitted ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Move the last specified elements to the beginning of the array

I have an array let colorsArr = ["red", "green", "purple", "pink", "black"]; Is there a way to retrieve a specific number of elements from the END and move them to the BEGINNING of the array? Desired result: example 1: //move last 3 elements let expec ...

Attempting to access the nested JSONObject within another JSONObject

I have this JSON I generated: { "error":false, "0":{ "tvInfo":{ "id":"0", "name":"The War of Thrones", "type_id":"1", "score":"8.1", "votes":"780", "created_date":"2011-04-17", ...

Creating a custom JSON structure in Rails allows developers to tailor the

My goal is to create a JSON response that mirrors an existing structure in our application, but in this case, I cannot use the jbuilder template. This is because the JSON data needs to be prepared for a live update job triggered from a model method, rather ...

React: Struggling to retrieve specific elements from an array stored in component state

For a fun side project, I've taken on the challenge of creating a miniature Pokedex app using React. import React, { Component} from 'react'; import './App.css'; import Card from './components/card/Card.component'; clas ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Using parameters to create unions in TypeScript

Is there a standard method to parametrically define a union? I'm searching for a way to generically define something like: type U<K> = T<K1> | T<K2> | ... | T<Kn> // Where K === (K1 | ... | Kn) Note: I'm encountering a s ...