【问题标题】:How to break ngFor loop in typescript如何打破打字稿中的ngFor循环
【发布时间】:2019-09-24 22:27:42
【问题描述】:

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

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
      }
    });
  }

【问题讨论】:

  • 在模板中使用执行 http 请求的函数不是一个好习惯。我建议您之前也从服务器获取所有数据以显示它们。

标签: html angular typescript ionic3


【解决方案1】:

作为最佳实践,您不应在视图中添加逻辑。

对于你的情况,你应该重写你的这样的东西:

您的 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/

【讨论】:

    猜你喜欢
    • 2017-11-17
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2015-10-04
    • 2013-08-31
    相关资源
    最近更新 更多