AngularJs从工厂获得员工

时间:2016-03-24 14:21:49

标签: javascript angularjs promise angular-promise angularjs-http

我在employeeController中收到了employeeFactoryemployeeFactory我收到employee这样的内容:

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;
    }

在我的控制器中,我试图像这样接收它:

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

但结果是null?

当我console.log我的requestFactory内的回复时,我收到employee个对象。我做错了什么?

2 个答案:

答案 0 :(得分:3)

背后的原因是,您错过了从requestFactory.post方法

返回factory.getEmployee的承诺

<强>代码

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('/');
  });
}

但即使你这样做,也无法获得打印的employee对象值。它将按$http.post方法/ $resource方法

打印promise对象返回

要获取该对象,您需要在该promise对象上使用.then函数。如下所示

employeeFactory.getEmployee($routeParams.id).then(function(employee){
   console.log('Employee', employee)
})

答案 1 :(得分:0)

我们可以在angularjs中使用延迟api,以便更好地在调用者和服务之间进行通信。

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;
}

在您的控制器上:

employeeFactory.getEmployee($routeParams.id).then(function(employee){
   console.log('Employee', employee)
},function(){
 $window.location.assign('/');
})

通过这种方法,如果您的响应延迟,我们可以通过一些消息通知来电者。 有关详细信息,请参阅此链接。 angular promises