Il mio servizio è:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
var deferred;
deferred = $q.defer();
this.initialized = deferred.promise;
this.user = {
access: false
};
this.isAuthenticated = function() {
this.user = {
first_name: 'First',
last_name: 'Last',
email: '[email protected]',
access: 'institution'
};
return deferred.resolve();
};
}
]);
Chiamo questo nel mio file config
via:
myApp.run([
'$rootScope', 'userService', function($rootScope, userService) {
return userService.isAuthenticated().then(function(response) {
if (response.data.user) {
return $rootScope.$broadcast('login', response.data);
} else {
return userService.logout();
}
});
}
]);
Tuttavia, si lamenta che then
non è una funzione. Non sto restituendo la promessa risolta?
@BenjaminGruenbaum Sì, hai ragione, non sapevo che '$ timeout' restituisce effettivamente una promessa, serviceMethod può essere abbreviato in: return $ timeout (function() {return {property: 'value'};}, 1000); – Brocco
Questo potrebbe funzionare, ma non è certamente un approccio consigliato per restituire le promesse –
@BenjaminGruenbaum che ho fatto, ora restituendo la promessa che genera $ timeout. – Brocco