角 - http.get返回undefined [英] Angular - http.get returning undefined
问题描述
我创建了一个工厂来获取客户:
customerModule.factory(CustomerFactory,[$ HTTP,DataService的功能($ HTTP,DataService的){ VAR自我=这一点;
self.page = 1;
self.query =; VAR queryFn =功能(查询){
self.query =查询;
$ http.get(dataService.baseURI +/客户,{
params:一个{
查询:self.query,
页:self.page,
每页:50
}
})。成功(功能(数据){
返回data.result;
});
}; 返回{
查询:queryFn
};
}]);
但是,当我在我的控制器使用它,它会返回未定义
,我不知道我在做什么错在这里?
$范围。$表(查询功能(){
如果($ scope.query&放大器;&放大器; $ scope.query.length→3){
的console.log(customerFactory.query($ scope.query));
}
否则如果($ scope.query.length 4;){
$ scope.customers = [];
}
});
如果你把你的 queryFn
函数仔细看你会发现你不是真正< STRONG>返回的任何事情。这意味着 queryFn
将返回未定义
。
所以第一步要修理你code是摆在 $ HTTP
前面收益
。
第二步是解决您正在调用 customerFactory.query
函数的方式。你指望它立即返回值,但是$ HTTP实际上创建了一个XHR请求,并XHR请求默认情况下异步,所以你不能指望 customerFactory.query
返回结果的时候了。
如果您还没有学会的承诺比这就是看一看他们的时候,因为他们使用的所有的地方,在世界上棱角分明。
假设你已经把收益
在$ HTTP,呼叫前 customerFactory.query
实际上将返回一个承诺对象。这一承诺对象有一个。然后
方法。此方法应被用来作为
customerFactory.query($ scope.query)
。然后(功能(客户){
的console.log(客户);
});
I've created a Factory to retrieve customers:
customerModule.factory("CustomerFactory", ["$http", "DataService", function ($http, dataService) {
var self = this;
self.page = 1;
self.query = "";
var queryFn = function (query) {
self.query = query;
$http.get(dataService.baseURI + "/customers", {
params: {
query: self.query,
page: self.page,
pageSize: 50
}
}).success(function (data) {
return data.result;
});
};
return {
query: queryFn
};
}]);
But when I use it in my controller, it returns undefined
, I'm not sure what I'm doing wrong here?
$scope.$watch("query", function () {
if ($scope.query && $scope.query.length > 3) {
console.log(customerFactory.query($scope.query));
}
else if ($scope.query.length < 4) {
$scope.customers = [];
}
});
If you take a close look at your queryFn
function you will notice that you're not actually returning anything from it. This means that queryFn
will return undefined
.
So the first step to fixing your code is to put return
in front of $http
.
Second step is fixing the way you are calling customerFactory.query
function. You expect it to return the value immediately, but $http actually creates an XHR request, and XHR requests are async by default, so you cannot expect customerFactory.query
to return the result right away.
If you haven't learned of promises than this is the time to take a look at them, because they are used all over the place, in angular world.
Assuming that you have put return
in front of $http, the call to customerFactory.query
will actually return a promise object. That promise object has a .then
method. This method should be used as:
customerFactory.query($scope.query)
.then(function(customers){
console.log(customers);
});
这篇关于角 - http.get返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!