回调值内的Angular 2函数不更新视图

com*_*you 7 javascript angular

我已经创建了函数和内部函数我在回调响应后调用一个回调函数我有更新字符串变量但这个字符串变量没有更新我的视图.

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;


            });
        }
}
Run Code Online (Sandbox Code Playgroud)

在html文件中

<h1>Balance = {{totlaBalance}} </h1>
Run Code Online (Sandbox Code Playgroud)

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"
    },
Run Code Online (Sandbox Code Playgroud)

在控制台值中显示但在视图中值不更新.
我正在使用第三方回调函数,它不允许使用箭头功能.

mic*_*yks 18

你只需要使用ArrowFunction(()=>)ChangeDetectionRef,如下所示,

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
             });
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 好的......但是你和TS一起工作,确保你使用箭头功能,否则会遇到困难的情况. (2认同)

Man*_*akh 14

回调逻辑应该在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;
    }));
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这在Angular 4中对我有用。 (2认同)