在Angular中,在闭包中引用服务属性/方法最合适的方式是什么?
What's the most appropriate way to reference a service property/method inside a closure in Angular?
我正在创建一个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,我会在variable1
声明上方添加var self = this;
,然后使用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
承诺的回调中时,this
不会作用域到你的服务实例。你还可以使用bind来更改回调中的上下文,使其作用域为服务实例。
但是当调用连续进行时可能会出现问题(并且因为服务是一个单例,它将是相同的this.variable1
,您将修改或覆盖最后返回的调用),不确定您正在尝试做什么,但最好的方法是从服务中的承诺回调返回数据。
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)
});
}
}
PSL这很好,但正如angular建议的那样,你应该在数组中调用依赖项,而不是函数参数,并且还需要返回服务以返回承诺。而最小化JavaScript代码依赖关系将保持不变。
authModule.service('authService', ['$http', '$sessionStorage', '$window', '$q', '$rootScope',
function(http, sessionStorage, window, q, rootScope) {
return 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) {
return q.reject(reason)
});
}
}]);
相关文章:
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- 在ng重复循环中显示条件内容的最佳方式是什么
- 在node.js中编写单元测试的最佳方式是什么
- 使用AJAX在Rails中提交动态表单的最佳方式是什么
- 使用Angular存储用户以前是否选中过复选框,然后再调用它的最佳方式是什么
- 在AngularJS中使用多个主题的最佳方式是什么
- 存储数据的最佳方式是什么,以便与jquery一起使用
- 为Google闭包类定义属性的首选方式是什么
- 用JavaScript随机给网页上的每个字母上色的最佳方式是什么
- 将JavaScript检测与MVC4显示模式集成的最佳方式是什么
- 正确的使用方式是什么.js与网络工作者
- 在客户端调整图像大小/裁剪图像的最佳方式是什么
- 大规模保存cookie的最佳方式是什么
- Vue.js中端到端(e2e)测试的正确方式是什么
- 在JavasciptMVC中存储常量值的最佳方式是什么
- 在angular js中,每次应用程序进入状态时,重新加载状态的最佳方式是什么
- 在项目中组织CSS/JavaScript的最佳方式是什么
- 在JavaScript中,最紧凑、最优雅、最高效的四舍五入方式是什么
- Angular:将对象存储在服务中以在视图中显示和将crud函数存储到服务器的最佳方式是什么
- Java开发人员在不编写Javascript的情况下生成Javascript的最佳方式是什么