Reputation: 3717
I'm creating an Angular service, and I wondered what the best practice is for the scenario below.
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) {
});
}
}
If I were using Knockout, I'd add var self = this;
above the variable1
declaration and then use self.variable1
instead of variable1
.
Is the use of var self = this;
the optimal practice, or is there a different preferred approach when using Angular?
Upvotes: 0
Views: 226
Reputation: 58
PSL this is good, But as angular suggest you should call dependencies in array instead of function params and also need to return service in order to return the promise. While minifying JavaScript code dependencies will remain same.
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)
});
}
}]);
Upvotes: 0
Reputation: 123739
You could just define it as a variable
var variable1 = true;
or
if you want to set it as instance property this.variable1 = true;
then you could do:-
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) {
});
Reason is the this
will not be scoped to the instance of your service when you are inside the callback of $http
promise. You can also use bind to change the context inside the callback to have it scoped to the service instance.
But there could be issues when the call is made consecutively (and because service is a singleton it will be the same this.variable1
you will be modifying or overwriting whichever call comes back last), not sure what exactly you are trying to do,but best thing would be to return the data from the promise callback in the service.
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)
});
}
}
Upvotes: 2