Skip to content

Instantly share code, notes, and snippets.

@swallentin
Last active November 18, 2015 10:35
Show Gist options
  • Save swallentin/dcc789c4df64292289cb to your computer and use it in GitHub Desktop.
Save swallentin/dcc789c4df64292289cb to your computer and use it in GitHub Desktop.
How to use Promises for the win
angular.module('myapp.security')
.factory('authentication', function ($http, $q, settings, authService) {
this._userContext = null;
var _this = this,
_fetchContext = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: settings.authentication.resourceEndPoints.context
})
.success(function (userContext) {
if (userContext) {
_this._userContext = userContext;
deferred.resolve(userContext);
}
deferred.reject(new Error('Load user context response was empty'));
})
.error(function (data, status) {
deferred.reject(new Error('Error thrown by $http when trying to load user context', data, status));
});
return deferred.promise;
},
_hasContext = function () {
return _this._userContext != null;
},
_authenticate = function (username, password) {
var deferred = $q.defer();
$http({
method: "POST",
url: settings.authentication.resourceEndPoints.login,
data: $.param({
j_username: username,
j_password: password
})
})
.success(function (data) {
if (data === "") {
deferred.reject("Response data was empty.");
return;
}
_this._userContext = data;
authService.loginConfirmed(_this._userContext);
deferred.resolve(data);
})
.error(function () {
deferred.reject(new Error('Error thrown by $http when calling login.'));
});
return deferred.promise;
},
_logout = function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: settings.authentication.resourceEndPoints.logout
})
.success(function () {
deferred.resolve(true);
})
.error(function () {
deferred.reject(new Error("Could not logout user."));
});
return deferred.promise;
};
return {
fetchContext: _fetchContext,
authenticate: _authenticate,
hasContext: _hasContext,
logout: _logout
};
});
angular.module('myapp.myservicemodule')
.factory('myservice', function ($http, $q, settings, authService) {
this._userContext = null;
var self = this
_get = function () {
var deferred = $q.defer();
$http({
method: "GET",
url: settings.myservice.resourceEndPoints.url
})
.success(function (data) {
if (data === "") {
deferred.reject("Response data was empty.");
return;
}
self._userContext = data;
deferred.resolve(data);
})
.error(function () {
deferred.reject(new Error('Error thrown by $http when calling login.'));
});
return deferred.promise;
};
return {
get: _get
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment