[英]How do I get the type from an object variable in Typescript / Angular 7?
[英]How do I change the type of a variable in Angular
我使用{{product.price.toLocaleString('en-US', {style: 'currency', currency: 'CAD'})}}
在我的視圖中顯示價格。 當我在 Angular 中手動鍵入數組中的值時,它正在工作。
現在我正在獲取數據庫以填充產品數組。
價格字段的類型為INT
數據庫結果被饋送到 angular 處理 ajax 請求和 json 編碼
顯示價格,但不顯示其后的 $CA。 我認為 function 沒有將此值視為Number
。
這是用於獲取我所有產品數據的 function。
sendGetRequest(){
this.http.get('http://localhost/ajax.php').subscribe((productList)=>{
this.productList=productList;
});
}
然后angular查看
<app-product data-ng-init="sendGetRequest()" (productAdded)="addProductToCart($event)" [products]="productList"> </app-product>
顯示的實際數據
<section *ngFor="let product of products" >
<div >
{{product.model}}
<br>
<div class="preView"><img src="./assets/{{product.img}}"></div>
{{product.price.toLocaleString('en-US', {style: 'currency', currency: 'CAD'})}}<br>
<button (click)="addProductToCart(product)">+</button><br>
</div>
</section>
所以我不確定我應該在哪里以及如何使用這種類型。
如果我將 function 更改為;
sendGetRequest(){
this.http.get('http://localhost/ajax.php').subscribe((productList)=>{
this.productList=productList.map(product=>{
product.price = +product.price; // cast to number
return product;
});
});
}
我收到警告;
“對象”類型上不存在屬性“地圖”
但是visual studio提供了一個快速修復,所以我已經嘗試過了,現在我的代碼看起來像;
private _productList: any;
public get productList(): any {
return this._productList;
}
public set productList(value: any) {
this._productList = value;
}
sendGetRequest(){
this.http.get('http://localhost/ajax.php').subscribe((productList)=>{
this.productList=productList.map(product=>{
product.price = +product.price; // cast to number
return product;
});
});
}
現在它正在工作,但我仍然收到 map 的錯誤;
src/app/store/store.component.ts:28:37 中的錯誤 - 錯誤 TS2339:“對象”類型上不存在屬性“地圖”。
28 this.productList=productList.map(product=>{
這是我的屏幕圖像
sendGetRequest(){
this.http.get('http://localhost/ajax.php').subscribe((productList)=>{
this.productList=productList.map(product=>{
product.price = +product.price; // cast to number
return product;
});
});
}
您只需要將其轉換為數字即可。 您正在接收字符串類型的價格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.