Angular2中回调函数内范围变量的访问值

Nis*_*thd 4 javascript asynchronous callback angular

我正在尝试从数据库检索数据并将其设置为范围变量。回调内的“this”不能作为 angular2 范围工作。我不知道为什么。我尝试过超时、区域。气事,无极事。我真的不知道它们是什么,所以我无法使用它。

  //in service.ts
  listFriends(callback) {
    result_data = [];

    db.transaction(function(tx) {

        tx.executeSql('SELECT * from mytable', [], function(tx, results) {

            length = results.rows.length;

            for (i = 0; i < length; i++) {

                //console.log(results.rows.item(i));
                result_data.push(results.rows.item(i))
            }
            callback(result_data);

        }, null);

    });

}
//in component.ts
public allmyFriends: any;
public self = this;
public test;
constructor(myFriendService: MyFriendService) {



    this.myFriendService = myFriendService;
    this.myFriendService.listFriends((response) => {
        //trying to set value to the scope variable.but not working
        this.test="test working";
        //same as above
        this.allmyFriends = response;
        //getting the response from the service successfully
        console.log("in list" + this.allmyFriends);

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

Thi*_*ier 5

当你说你尝试过区域时。你到底是什么意思?您是否注入 NgZone 并在其中执行代码。

这个问题可以给你一些提示:View is not Updated on Change in Angular2

从哪里获取地图实例。如果它是在区域之外实例化的,Angular2 将无法检测到mapLatitudeInput属性的更新。

你可以尝试这样的事情:

export class MapComponent {
  constructor(ngZone:NgZone) {
    this.ngZone = ngZone;
  }

  someMethod() {
    this.myFriendService.listFriends((response) => {
      this.ngZone.run(() => {
        this.test="test working";
        this.allmyFriends = response;
        console.log("in list" + this.allmyFriends);
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

这个问题也可能与您的问题有关:Angular2 child propertychange notfire update onbound property

希望它对你有帮助,蒂埃里