AngularJs get employee from factory

China☆狼群 提交于 2020-01-04 06:09:03

问题


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



来源:https://stackoverflow.com/questions/36202468/angularjs-get-employee-from-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!