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

Javascript Angular2中回调函数内范围变量的访问值,javascript,asynchronous,callback,angular,Javascript,Asynchronous,Callback,Angular,我试图从DB中检索数据,并将其设置为scope变量。“this”在回调中不作为angular2作用域工作。我不知道为什么。我试过暂停,区域。加油,承诺。我真的不知道它们是什么,所以我无法利用它们 //in service.ts listFriends(callback) { result_data = []; db.transaction(function(tx) { tx.executeSql('SELECT * from mytable', [],

我试图从DB中检索数据,并将其设置为scope变量。“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);

    } );
  }
//在service.ts中
listFriends(回调){
结果_数据=[];
数据库事务(功能(tx){
tx.executeSql('从mytable中选择*,[],函数(tx,结果){
长度=results.rows.length;
对于(i=0;i{
//正在尝试将值设置为范围变量。但不起作用
this.test=“测试工作”;
//同上
this.allmyFriends=响应;
//成功从服务获取响应
console.log(“登录列表”+this.allmyFriends);
} );
}

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

这个问题可以给你一些提示:

从何处获取地图实例。如果在区域外实例化,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);
      });
    });
  }
此问题也可能与您的问题有关:

希望它能帮助你,
蒂埃里

天哪!NgZone。跑()像个魔术师一样工作。非常感谢你,蒂埃里。我用过这个_ngZone.runOutsideAngular()一,这就是它不起作用的原因。你知道吗?酷!听到这个消息很高兴;-)
runOutsideAngular
方法用于在触发Angular2变化检测的区域之外的Angular2之外执行一些处理。因此,这种行为似乎很正常……如何测试
函数中的代码?i、 e.确保设置了私有变量?