我正在创建一个 Angular 服务,我想知道以下场景的最佳实践是什么。
authModule.service('authService',
function($http, $sessionStorage, $window, $q, $rootScope) {
this.variable1 = true;
this.processVariable = function () {
return $http({...}).then(function(response) {
variable1 = response.data;
//line above this will throw an error because it's not scoped
}, function (reason) {
});
}
}
如果我使用 Knockout,我会添加 var self = this;
上面variable1
声明然后使用 self.variable1
而不是variable1
.
是使用var self = this;
最佳实践,或者使用 Angular 时是否有不同的首选方法?
最佳答案
您可以将其定义为变量
var variable1 = true;
或
如果要将其设置为实例属性this.variable1 = true;
那么你可以这样做:-
var _that = this;
this.processVariable = function () {
return $http({...}).then(function(response) {
_that.variable1 = response.data;
//line above this will throw an error because it's not scoped
}, function (reason) {
});
原因是当您位于 $http
Promise 的回调中时,this
的作用域不会限于您的服务实例。您还可以使用bind更改回调内的上下文以将其范围限定为服务实例。
但是连续进行调用时可能会出现问题(并且因为服务是单例,所以您将修改或覆盖最后返回的调用的 this.variable1
),而不是确定您到底想做什么,但最好的办法是从服务中的 promise 回调返回数据。
authModule.service('authService',
function($http, $sessionStorage, $window, $q, $rootScope) {
this.processVariable = function () {
return $http({...}).then(function(response) {
return response.data;
//line above this will throw an error because it's not scoped
}, function (reason) {
$q.reject(reason)
});
}
}
关于javascript - 在 Angular 闭包内引用服务属性/方法的最合适方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267920/