corry corry - 12 days ago 6
AngularJS Question

AngularJS get value from service function

I have a problem with getting value from service in my controller.
I get the value from API using service:

angular.module('app').factory('service',
['$q', '$rootScope', '$timeout', '$http',
function ($q, $rootScope, $timeout, $http) {

// create user variable
var user = null;

// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
getEmail: getEmail
});

function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}

function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}

function login(username, password) {

// create a new instance of deferred
var deferred = $q.defer();

// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});

// return promise object
return deferred.promise;

}

function getEmail() {
// create a new instance of deferred
var deferred = $q.defer();

$http.get('/email/'+$rootScope.username)
.success(function (data) {
console.log(data);
deferred.resolve();
})
.error(function (data) {
deferred.reject();
})

return deferred.promise;
}
}]);


and I'm trying to get and use value in the controller:

angular.module('app')
.controller('myController', ['$rootScope', '$scope', '$state', '$http', '$q', 'service', function ($rootScope, $scope, $state, $http, $q, service) {

$scope.email;

$scope.getEmail = function() {
// call getEmailFromDB from service
service.getEmail()
// handle success
.then(function (data) {
$scope.email = data; //here I got undefined
console.log($scope.email);
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "wrong@mail.com";
});
};
$scope.getEmail();
}]);


but in the controller there is
undefined
value.

In my console:
enter image description here

Regarding the documentation of $q, I use function then() in service and controller

Does anybody know where is the problem?

Answer

you forgot to send your result in your service like this

deferred.resolve(data);
Comments