Angular 2 function inside callback value not updating view

I created a function and an internal function. I call one callback function after the callback is answered. I have an update string variable, but this string variable does not update my view.

import { Component } from 'angular2/core'; 

@Component({
    selector : "myview"
    templateUrl : 'app/view/myview.component.html'
})


export class ViewComponent {

        getAddress : string;
        public totlaBalance : string;

        getBalance():void{
             var self = this;
             getBalanceData(this.getAddress,function(error,res){
                 console.log(res);
                 self.totlaBalance = res;


            });
        }
}

In html file

<h1>Balance = {{totlaBalance}} </h1>

package.js

 "dependencies": {
        "angular2": "2.0.0-beta.15",
        "systemjs": "0.19.26",
        "es6-shim": "^0.35.0",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.2",
        "zone.js": "0.6.10",
        "bootstrap": "^3.3.6"
    },

The console value displays the value but does not.
I use a third-party callback function that does not allow the use of the arrow function.

+4
source share
2 answers

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

Angular.

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

Source: https://habr.com/ru/post/1655681/


All Articles