【发布时间】:2018-06-24 07:21:34
【问题描述】:
有一个从 json 列出的产品列表,我放置了分配有相应产品 ID 的 BUY 按钮。当我按下 Buy 按钮时,应该下订单。我可以将数据绑定到属性 (prodID),但我无法在数组 body[] 中分配变量 prodID 。我无法使用 json 下订单,因为需要产品 ID,我无法正确分配它
这是我的代码 app.component.ts
import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { Woocommerce } from './Woocommerce';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
result: any ;
prodID: number;
constructor(private http: HttpClient ){ }
baseURL = 'https://wc.example.com/wp-json/wc/v2';
products = 'products';
consumer_key = 'ck_xxxxxxxxxxxxxxxxxx';
consumer_secret = 'cs_xxxxxxxxxxxxxxxxxx';
body = {
payment_method: 'paypal',
payment_method_title: 'Direct Bank Transfer',
set_paid: true,
line_items: [
{
product_id: this.prodID,
quantity: 1
}
]
};
getProductDetails(){
this.http.get<Woocommerce>(`${this.baseURL}/${this.products}?consumer_key=${this.consumer_key}&consumer_secret=${this.consumer_secret}`).subscribe(
data => {
this.result = data;
console.log(this.result);
});
}
buyNow(getID: any) {
this.prodID = getID;
this.http.post<Woocommerce>(`${this.baseURL}/orders?consumer_key=${this.consumer_key}&consumer_secret=${this.consumer_secret}`, this.body, {
headers: new HttpHeaders().set('Content-Type', 'application/json' ),
}
).subscribe(resp => {console.log(resp);});
}
ngOnInit(): void {
this.getProductDetails();
}
}
还有app.component.html
<h1>Woocommerce</h1>
<form>
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<td scope="col">ID</td>
<td scope="col">Name</td>
<td scope="col">Price</td>
<td scope="col">Product Image</td>
<td scope="col">Buy</td>
</tr>
</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>
【问题讨论】:
标签: javascript json angular api typescript