dub*_*uga 4 javascript angularjs angularjs-service
如何通过"this"关键字periodicFetch()调用它$interval?
这是我的角度应用程序的代码:
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();
});
Run Code Online (Sandbox Code Playgroud)
目前的输出是:
Object {foo: null}
undefined
undefined
undefined
...
Run Code Online (Sandbox Code Playgroud)
它似乎适用于没有的第一次调用$interval.但在$interval价值内this.variables似乎是undefined.
Ale*_* T. 10
尝试使用.bind,就像这样
$interval(this.periodicFetch.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
840 次 |
| 最近记录: |