AngularJs 从工厂获得员工 [英] AngularJs get employee from factory

查看:49
本文介绍了AngularJs 从工厂获得员工的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 employeeFactory 中有一个 employeeController 和一个 employeeFactory 我收到一个 employee 像这样:

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

但结果为空?

当我 console.log 在我的 requestFactory 中响应时,我收到一个 employee 对象.我做错了什么?

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

推荐答案

背后的原因是,你错过了从 factory.getEmployee 方法返回 requestFactory.post 的承诺

Reason behind it is, you missed to return promise of requestFactory.post from factory.getEmployee method

代码

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 方法

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

为了获得该对象,您需要在该承诺对象上使用 .then 函数.如下图

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

这篇关于AngularJs 从工厂获得员工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆