【问题标题】:AngularJS: Using "this" in an interval function within a serviceAngularJS:在服务的间隔函数中使用“this”
【发布时间】:2015-12-07 13:22:29
【问题描述】:

当通过$interval 调用时,如何让periodicFetch() 使用“this”关键字?

这是我的 Angular 应用程序的代码:

angular.module('myapp', []);

var MyService = function($rootScope, $http, $interval) {
    this.variables = {};

    this.registerVariable = function(varName) {
        this.variables[varName] = null;
    };

    this.periodicFetch = function() {
        console.log(this.variables);
    };

    this.run = function() {
        this.periodicFetch();
        $interval(this.periodicFetch, 1000);
    };
};

angular.module('myapp').service('myService',
        ['$rootScope', '$http', '$interval', MyService]);

angular.module('myapp').run(function(myService) {
    myService.registerVariable('foo');
    myService.run();
});

目前的输出是:

Object {foo: null}
undefined
undefined
undefined
...

它似乎适用于没有$interval 的第一次调用。但在$interval 内,this.variables 的值似乎是undefined

【问题讨论】:

    标签: javascript angularjs angularjs-service


    【解决方案1】:

    尝试使用.bind,像这样

    $interval(this.periodicFetch.bind(this), 1000);
    

    Example

    【讨论】:

    • 感谢您简洁而有帮助的回答!
    【解决方案2】:

    this 指的是函数作用域。一种选择是将对它的引用存储在变量中,通常命名为 self。 var self = this;,但是使用 bind 是正确的答案。

    【讨论】:

    • 感谢您的解释!
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多