繁体   English   中英

如何更改 Angular 中的变量类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM