如何在打字稿中打破ngFor循环

时间:2019-05-07 09:28:47

标签: html angular typescript ionic3

我正在使用Ionic-3开发混合应用程序。我正在尝试从Html调用函数,并使用此函数从typescript返回一些值,但是我看到该函数被多次调用,并且浏览器和应用程序挂起。我的html和打字稿功能如下。

  

HTML

  <div *ngFor="let product of myCourier">
    <ion-row>
      <ion-col col-6> Charge</ion-col>
      <ion-col col-6>Rs. {{getcharge(product)}}</ion-col>
    </ion-row>
  </div>
  

打字稿

   getcharge(item){
    var dat: { [k: string]: any } = {};
    dat.toaddress = item.to_address
    dat.fromaddress = item.from_address
    this.httpClient.post(this.config.url + 'getrate.php', dat).subscribe((data: any) => {
      if (data.ResponseCode == 1) {
        var charge = data.charge
        console.log(charge)
        return charge
      }
    });
  }

1 个答案:

答案 0 :(得分:0)

作为最佳做法,您不应在视图内部添加逻辑。

对于您的情况,您应将您的内容重写为以下内容:

  

您的HTML(无函数调用,仅product

<div *ngFor="let product of myCourierProducts">
  <ion-row>
    <ion-col col-6> Charge</ion-col>
    <ion-col col-6>Rs. {{product}}</ion-col>
  </ion-row>
</div>
  

您的TS

ngOnInit() { // Or wherever you set your myCourier variable
    for (i=0; i<5; i++) {
        myCourier[i] = SOMETHING
        myCourierProducts[i] = getcharge(SOMETHING)
    }
}

getcharge(item){
    var dat: { [k: string]: any } = {};
    dat.toaddress = item.to_address
    dat.fromaddress = item.from_address
    this.httpClient.post(this.config.url + 'getrate.php', dat).subscribe((data: any) => {
        if (data.ResponseCode == 1) {
            var charge = data.charge
            console.log(charge)
            return charge
        }
    });
}

重要的是要提到MVVM Angular architecture中的component(“模型”)不是用于复杂的逻辑,而是用于指向视图的小型逻辑。

复杂的逻辑应该放在services内。

https://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/

相关问题