简体   繁体   English

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

[英]Access value of the scope variable inside callback function in Angular2

I'm trying to retrieve data from DB and set it to the scope variable.'this' inside a callback not working as a angular2 scope. 我正在尝试从数据库中检索数据并将其设置为范围变量。这在回调内部不能作为angular2范围。 I don't know why. 我不知道为什么。 I tried timeout, zone. 我试过超时,区域。 gas things, Promise things. 气东西,无极的东西。 I don't really know what they are, so I can't able to make use of it. 我真的不知道它们是什么,所以我无法使用它。

  //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);

    } );
  }

When you said that you tried zone. 当你说你试过区域。 What do you mean exactly? 你到底是什么意思? Do you inject NgZone and execute code within it. 你注入NgZone并在其中执行代码。

This question could give you some hints: View is not updated on change in Angular2 . 这个问题可以给你一些提示: 视图没有更新Angular2中的更改

From where do you get your map instance. 从哪里获得地图实例。 If it's instantiated outside a zone, Angular2 won't be able to detect updates of the mapLatitudeInput attribute. 如果它在区域外实例化,Angular2将无法检测到mapLatitudeInput属性的更新。

You could try something like that: 你可以尝试这样的事情:

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

This question could be also related to your problem: Angular2 child property change not firing update on bound property . 此问题也可能与您的问题有关: Angular2子属性更改未在绑定属性上触发更新

Hope it helps you, Thierry 希望它对你有帮助,蒂埃里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM