javascript - Angular2 中回调函数中作用域变量的访问值

标签 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);

    } );
  }

最佳答案

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

这个问题可以给你一些提示:View is not updated on change in Angular2 .

你从哪里得到你的 map 实例。如果它在区域外实例化,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);
      });
    });
  }

这个问题也可能与您的问题有关:Angular2 child property change not firing update on bound property .

希望对你有帮助, 蒂埃里

关于javascript - Angular2 中回调函数中作用域变量的访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849970/

相关文章:

node.js - 如何防止每条新推文触发 Twitter 流中的回调?

c# - 如何在没有回发的情况下更改同一页面上的查询字符串

javascript - 了解Node.JS使用async.waterfall如何执行外部功能

javascript - 我正在尝试调用 JavaScript 函数,但无法访问它,因为显然它是 'undefined'

Python 异步生成器不是异步的

java - 在 Android 中访问字符串数组中的最后一个 "number"元素

node.js - 使用 PassportJS,如何将额外的表单字段传递给本地身份验证策略?

ruby-on-rails - 如果 after_initialize 回调返回 false,则返回 nil 对象

javascript - Three.js 从子对象获取父对象(一组)

javascript - 如何避免这种情况? Yslow -> "This page has 5 external stylesheets. Try combining them into one."