AngularJs得到工厂的员工 [英] AngularJs get employee from factory
问题描述
我有一个 employeeController
和 employeeFactory
在 employeeFactory
我收到员工
是这样的:
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
我收到员工
对象。我在做什么错了?
When I console.log
the response in my requestFactory
I receive an employee
object. What am I doing wrong?
推荐答案
背后的原因是,你错过了从 requestFactory.post
的承诺> factory.getEmployee 法
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('/');
});
}
但是,即使你这样做,你将不能够获得价值员工
对象打印。它会通过打印对象的承诺回报 $ http.post
方法/ $资源
法
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)
})
这篇关于AngularJs得到工厂的员工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!