Angular 5 - 无法分配类属性
Posted
技术标签:
【中文标题】Angular 5 - 无法分配类属性【英文标题】:Angular 5 - Can't get assign the class property 【发布时间】: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 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>
【问题讨论】:
【参考方案1】:在您的情况下,它只是为 body variable 创建初始状态的副本,因此它将始终返回 undefined。
下面是解决方法
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););
【讨论】:
有什么办法可以分成两个组件,比如在一个组件中列出产品并在另一个组件中购买产品。??? @PrakashGD,是的,您可以这样做,因为您需要创建一个公共服务并在这些组件中使用它。以上是关于Angular 5 - 无法分配类属性的主要内容,如果未能解决你的问题,请参考以下文章
无法将符合协议的 Objective-C 类分配给具有 Swift 协议的属性
如何从类属性 TypeScript 中侦听值更改 - Angular