Return result to parent function
I am pulling my hair out here. I am using ion-autocomplete and want to retrieve data using a factory.
My Factory ...
myApp.factory('items', function($http){
return {
list: function(query,callback){
$http.get('http://192.168.100.100/myApp/products/' + query).success(callback)
}
};
});
To get the data I am using.
items.list(function(items) {
$scope.items = items;
});
Demo for autocomplete query data, eg ..
$scope.getTestItems = function (query) {
return {
items: [
{id: "1", name: query + "1", view: "view: " + query + "1"},
{id: "2", name: query + "2", view: "view: " + query + "2"},
{id: "3", name: query + "3", view: "view: " + query + "3"}]
};
};
So, I believe this is an acceptable solution.
$scope.getTestItems = items.list(query,function(items)
{
console.log(items);
return items;
}
)
but clearly not. I tried..
$scope.getTestItems = function(query)
{
items.list(query,function(items)
{
console.log(items);
return items;
}
)
}
Which gives me the console of the result, but that doesn't fall back to getTestItems
+3
source to share
3 answers
As per the docs (assuming I have rights here), you can return the promise
myApp.factory('items', function($http){
return {
list: function(query) {
return $http.get(... + query).then(function(res) {
return res.data; // unwrap the response data
// see the "Returns" section at https://docs.angularjs.org/api/ng/service/$http#usage
});
}
};
});
and controller
$scope.getTestItems = function(query) {
return items.list(query);
};
0
source to share
How about this
Factory
list: function(query,callback){
return $http.get('http://192.168.100.100/myApp/products/' + query)
}
This way you are returning a promise from the factory.
controller
$scope.getTestItems = function(query){
items.list(query).then(function(items){
console.log(items);
});
}
The callback will be executed as soon as the promise is reached.
0
source to share
you can try this,
myApp.factory('items', function($http){
return {
list: function(query){
return $http.get('http://192.168.100.100/myApp/products/'+query);
}
};
});
then in your controller
var promise = items.list(query);
promise.then(function(response){
//here we go
$scope.items = angular.fromJson(JSON.parse(response.data));
});
0
source to share