Angularjs Get Employee From Factory
I've got a employeeController and a employeeFactory in the employeeFactory I receive an employee like this: function employeeFactory(authenticationFactory,requestFactory,GLOBALS) {
Solution 1:
Reason behind it is, you missed to return promise of requestFactory.post
from factory.getEmployee
method
Code
factory.getEmployee = function(id) {
data = {"api_token": authenticationFactory.getToken()};
url = GLOBALS.url + 'show/employee/' + id;
return requestFactory.post(url, data)
.then(function (response) {
return vm.employee = response.data.result.Employee;
}, function () {
$window.location.assign('/');
});
}
But even though you do it, you will not able to get value employee
object printed. It will print promise object return by $http.post
method/ $resource
method
For getting hold on that object you need to use .then
function over that promise object. like below
employeeFactory.getEmployee($routeParams.id).then(function(employee){
console.log('Employee', employee)
})
Solution 2:
We can use deferred api in angularjs for better communication between caller and service.
factory.getEmployee = function(id) {
var deferred = $q.defer();
data = {"api_token": authenticationFactory.getToken()};
url = GLOBALS.url + 'show/employee/' + id;
return requestFactory.post(url, data)
.then(function (response) {
deferred.resolve(response.data.result.Employee);
}, function () {
deferred.reject();
});
return deferred.promise;
}
On your controller:
employeeFactory.getEmployee($routeParams.id).then(function(employee){
console.log('Employee', employee)
},function(){
$window.location.assign('/');
})
By this approach we can notify caller with some messages if your response gets delayed. For more info see this link. angular promises
Post a Comment for "Angularjs Get Employee From Factory"