AngularJs get employee from factory

2019-07-17 17:33发布

问题:

I've got a employeeController and a employeeFactory in the employeeFactory I receive an employee like this:

function employeeFactory(authenticationFactory,requestFactory,GLOBALS) {
        var factory = {};
        var vm = this;
        vm.employee = {};

        factory.getEmployee = function(id) {
            data = {"api_token": authenticationFactory.getToken()};
            url = GLOBALS.url + 'show/employee/' + id;
            requestFactory.post(url, data)
                .then(function (response) {
                    return vm.employee = response.data.result.Employee;
                }, function () {
                    $window.location.assign('/');
                });
        }
        return factory;
    }

In my controller I'm trying to receive it like this:

console.log(employeeFactory.getEmployee($routeParams.id));

But the result is null?

When I console.log the response in my requestFactory I receive an employee object. What am I doing wrong?

回答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)
})


回答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