2

I'm developing Hybrid app using Ionic-3. I'm trying to call function from Html and get some values return from typescript with this function but i see the function is call multiple times and my browser and application is hang. My html and typescript function is below.

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>

Typescript

   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
      }
    });
  }
Mouad Ennaciri
  • 1,217
  • 3
  • 15
  • 28
Sandip Moradiya
  • 706
  • 1
  • 11
  • 30
  • 2
    It is not good practice to use a function that do an http request in a template. I suggest you too get all your data from server before to display them. – V. Pivet May 07 '19 at 09:52

1 Answers1

0

As best practices, you shouldn't add logic inside the view.

For your case, you should rewrite your for something like this:

Your HTML (No function call, just 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>

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

It is important to mention that the component ("Model"), in the MVVM Angular architecture is not for complex logic, it is for small logic directed to the View.

The complex logic should be placed inside services.

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

Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57