Angular 2 function inside callback value not updating view

后端 未结 2 940
谎友^
谎友^ 2021-02-06 06:17

I have created function and inside function i\'m calling one callback function after callback response I have update string variable but this string variable not updating my vie

相关标签:
2条回答
  • 2021-02-06 07:03

    You just need to use ArrowFunction (()=>) and ChangeDetectionRef as shown below,

    import {Injectable, ChangeDetectorRef } from 'angular2/core';  //<<<===here
    
    export class ViewComponent {
        getAddress : string;
        public totlaBalance : string;
    
         constructor(private ref: ChangeDetectorRef){}             //<<<===here
    
         getBalance():void{
                 var self = this;
                 getBalanceData(this.getAddress,(error,res)=>{    //<<<===here
                     console.log(res);
                     self.totlaBalance = res;
                     self.ref.detectChanges();                    //<<<===here
                 });
         }
    }
    
    0 讨论(0)
  • 2021-02-06 07:20

    The callback logic should be run within Angular Zone.

    import { Component, NgZone } from '@angular/core'; 
    
    @Component({
      selector: "myview"
      templateUrl: 'app/view/myview.component.html'
    })
    
    export class ViewComponent {
      getAddress: string;
      public totalBalance: string;
    
      constructor(private ngZone: NgZone) {}
    
      getBalance(): void {
        getBalanceData(this.getAddress, (error, result) => this.ngZone.run(() => {
          console.log(result);
          this.totalBalance = result;
        }));
      }
    }
    
    0 讨论(0)
提交回复
热议问题