angular using $http in factory - angularjs

I seem to be having an issue sending json from my factory out to controllers
Here is my factory
.factory("UserService", function($http) {
var LevelsHere;
$http.get("/assets/images/generated.json").success(function(data){
LevelsHere = data;
return LevelsHere;
});
return {
all: function() {
return LevelsHere;
},
first: function() {
return LevelsHere[0];
}
};
})
I am simply trying to send the json object out (or bits of it) with this factory. I can console.log inside the http get and it seems to be grabbing the json just fine. I seem to have hit a wall, any help would be much appreciated. I would just like the all ad first functions to be working. thanks!
I first had success by hard coding the levelsHere above it with the json string like var levelsHere = [{"stuff in here"}], but when i moved it over to an $http it doesn't work.

Since you don't have any $watch to look over the value returned from asynchronous $http.get request, the updated value is not available to the consumer. As $http.get request returns a promise, you can leverage the promise and update the value on success of the promise in then() as below:
var app = angular.module('app', [])
.factory("UserService", function($http) {
var LevelsHere = $http.get("https://api.github.com/users/mralexgray/repos")
.success(function(data){
return data;
});
return {
all: function() {
return LevelsHere;
}
};
})
.controller('controller', function(UserService, $scope){
UserService.all().then(function(data){
$scope.value = data;
});
})
DEMO

What is not working exactly? My guess is that you got undefined immediately after this factory method, since $http uses deferred object

You are returning LevelsHere before the async call is finished. The order of your operation goes:
call http.get
return all and first which return LevelsHere (even though the http request has not finished)
http get returns json
success call back fires returning LevelsHere to nobody.
A better way is to just return the promise:
return $http.get("/assets/images/generated.json")
then in your controller you can get the value from the promise by calling the success function. If you try to resolve the promise in the factory and return the value, your controller will try to use the value before it's returned from the server.
var promise = UserService()
promise.success(function(data){
// do something with data
}

Related

Using the service data in the controller

I have placed the service and the controller in the same js file. So Im trying to fetch the data from the service and use it in my html. In my code Im able to generate the data from the service but not able to assign it to a $scope in the controller and use it in the html. So how do I get the data and assign it to the $scope so that I can use it in my html.
var app = angular.module("app",[]);
app.factory('factoryServices',function($http){
var newObject = {};
var _getChart= function(){
$http.get("http://citibikenyc.com/stations/json")
.success(function(data, status){
if(data) {
return data;
}
}).error(function(data,status){
return error;
});
}
newObject.getChart = _getChart;
return newObject;
});
app.controller("chartController",function($scope,$http,factoryServices){
factoryServices.getChart($scope.chartServicesCompleted);
$scope.chartServicesCompleted = function(data){
$scope.serviceResponse = data;
}
})
If you rewrite your code like this, it should work as expected:
var app = angular.module("app",[]);
app.factory('factoryServices',function($http){
var newObject = {};
var _getChart= function(){
return $http.get("http://citibikenyc.com/stations/json")
.then(function(response){
if(response.data) {
return response.data;
}
}, function(response){
console.error("getChart failed with ",response);
});
}
newObject.getChart = _getChart;
return newObject;
});
and your controller
app.controller("chartController",function($scope,$http,factoryServices){
factoryServices.getChart().then(chartServicesCompleted);
function chartServicesCompleted(data){
$scope.serviceResponse = data;
}
})
The reason your initial code doesn't work, is because your getChart doesn't actually take an argument. So passing your callback like this: getChart($scope.chartServicesCompleted) doesn't do anything. In the rewritten code, I've made it so the getChart function returns the promise created by $http.get(..) which then allows you to use .then([callback]) in your controller.
you are passing a callback function but not handling inside the service method.
do change as
var _getChart= function(callback){
$http.get("http://citibikenyc.com/stations/json")
.success(function(data, status){
callback(data);
}).error(function(data,status){
callback(data);
});
}
now factoryServices.getChart($scope.chartServicesCompleted); will work
you can make more generic by handling success and error callback separately.
or one more way is to implement the success and error logic inside your controller.
but do not forget to check the function type i.e
if(typeof callback == 'function'){
callback(data);
}
Edit: as per advanced you call implement promises.
if you are using angular version 1.6, the success and error methods have been depreciated.
secondly you can do inside service return the http object
var _getChart= function(){
return $http.get("http://citibikenyc.com/stations/json");
}
and then handle the promise in the controller like
factoryServices.getChart().then(successMethod, error method);
Let the service return the promise to the controller. ex:
var _getChart= function(){
return $http.get("http://citibikenyc.com/stations/json");
}
and in the controller handle the promise. Use 'then' instead
factoryServices.getChart().then(function(response){var theDate = response.data},function(error){});
you can declare methods instead in the controller for handling the success and error
factoryServices.getChart).then(onSuccess,onError);
Don use the .success method and .error method. They dont't behave as other promises. So get used to 'then'
You really don't need to handle errors in the service method.I use angular interceptors in most of the cases. Check em out. But sometimes you need to handle the error in the controller. So its good to get the callback in the controller

Angular directive without timeout service does not work

In angularJS, I have written a directive to display data. This data is fetched by a http service from remote database.
If I apply below timeout service in code, then result is displayed on the html page as http service returns in one second.
$timeout(function () {
$scope.treeRoot = $scope.$eval('serviceResult') || {};
}, 1000);
If i do not use timeout service, then page does not show any data because $scope.treeRoot is empty e.g.
$scope.treeRoot = $scope.$eval('serviceResult') || {};
In production, the http service can take time more than one second to return, is there any generic solution.
You should use Angular's promises or $http service which allows to return a promise.
After the promise, e.g. $http request, is resolved, you can populate $scope.treeRoot with the results.
Let me know if that helps.
AS suggested in one answer you have to use the $http promises and capture the result in response.
Here is an example with some code.
Service:
app.factory('myService', ['$http',
function($http){
var obj = {};
obj.get = function (q) {
return $http.get('/your_get_url')
};
obj.post = function (q, object) {
return $http.post('/your_post_url', object)
};
return obj;
}
]);
In your controller,
allControllers.controller('changePasswordController', ['$scope','myService',
function($scope,myService) {
myService.get().then(function (result) {
$scope.treeRoot = 'use your result here'
},function error(result)
{
console.log(result)
})
}
])
This replaces your timeout issue.

How can I create a service that returns the value promise

I want to create a service that returns a json
Or by request to to the server, or by checking if it exists already in: Window.content
But I don't want to get a promise from my Controller !
I want to get the json ready !
I have tried several times in several ways
I tried to use with then method to do the test in my Service
but I still get a promise
( Whether with $http only, and whether with $q )
I could not get the value without getting promise from my Controller
My Service :
app.service('getContent',['$http', function( $http ){
return function(url){ // Getting utl
if(window.content){ // if it's the first loading, then there is a content here
var temp = window.content;
window.content = undefined;
return temp;
}
return $http.get(url);
};
}]);
My Controller:
.state('pages', {
url: '/:page',
templateProvider:['$templateRequest',
function($templateRequest){
return $templateRequest(BASE_URL + 'assets/angularTemplates/pages.html');
}],
controller: function($scope, $stateParams, getContent){
// Here I want to to get a json ready :
$scope.contentPage = getContent(BASE_URL + $stateParams.page + '?angular=pageName');
}
});
If the data exists, just resolve it in a promise.
While this process is still asynchronous it won't require a network call and returns quickly.
app.service('getContent',['$http', '$q', function( $http, $q ){
return function(url){
// create a deferred
var deferred = $q.defer();
if(window.content){ // if it's the first loading, then there is a content here
var temp = window.content;
window.content = undefined;
deferred.resolve(temp); // resolve the data
return deferred.promise; // return a promise
}
// if not, make a network call
return $http.get(url);
};
}]);
Just to reiterate, this asynchronous, but it won't require a network call.
This is not possible. If the code responsible to calculate or retrieve the value relies on a promise, you will not be able to return the value extracted from the promise by your function.
Explanation: This can easily be seen from the control flow. A promise is evaluated asynchronously. It may take several seconds to retrieve json from a server, but the caller of your function should not wait so long because your whole runtime environment would block. This is why you use promises in the first place. Promises are just a nice way to organize callbacks. So when your promise returns, the event that caused the function call will have already terminated. In fact it must have, otherwise your promise could not be evaluated.
You're thinking about this wrong. A service always returns a promise, because there is no synchronous way of getting JSON from an API:
app.factory('myService', ['$http', function($http) {
return $http('http://my_api.com/json', function(resp) {
return resp.data;
});
}]);
You would then call this within your controller like so:
app.controller('myController', ['$scope', 'myService', function($scope, myService) {
myService.then(function(data) {
$scope.contentPage = data; // here is your JSON
}, function(error) {
// Handle errors
});
}]);
Your service is returning a promise as it's written at the moment. A promise is always a promise, because you don't really know when it will be finished. However with Angular's 2 way data binding this isn't an issue. See my edits bellow as well as the example on $HTTP in the docs
In your controller
controller: function($scope, $stateParams, getContent){
getContent(BASE_URL + $stateParams.page + '?angular=pageName')
.then(aSuccessFn, aFailedFn);
function aSuccessFn(response) {
// work with data object, if the need to be accessed in your template, set you scope in the aSuccessFn.
$scope.contentPage = response.data;
}
function aFailedFn(data) {
// foo bar error handling.
}
}

Angularjs .factory method return

I have been able to get this .factory to work by adding a "return" in front of both the Restangular.all statement and the response. My question is why is it needed there? Why can't I just return the response?
app.controller('MainController', ['GetIndexesFromES', '$scope', function(GetIndexesFromES, $scope) {
$scope.indices = GetIndexesFromES.getUniqueIndexIDs();
console.log($scope.indices);
}]);
app.factory('GetIndexesFromES', ['Restangular', function GetIndexesFromES (Restangular) {
var GetIndexesFromES = {};
GetIndexesFromES.getUniqueIndexIDs = function(){
return Restangular.all('_stats/index,store').getList().then(function(response) {
return response
});
}
return GetIndexesFromES;
}]);
The main reason why I'm asking this question is that I want to modify the data (within the .factory) before sending it back to the controller/$scope.
Thank you,
Gregg
If you carefully look at your code for getUniqueIndexIDs you will realize there is a callback.
The second return is not a return from getUniqueIndexIDs but from your then's callback function.
Essentially your getUniqueIndexIDs returns a promise created by then. This promise is resolved by the return value then callback function which in your case is return response.
What you are essentially doing is promise chaining.

How to wait till the response comes from the $http request, in angularjs?

I am using some data which is from a RESTful service in multiple pages.
So I am using angular factories for that. So, I required to get the data once from the server, and everytime I am getting the data with that defined service. Just like a global variables. Here is the sample:
var myApp = angular.module('myservices', []);
myApp.factory('myService', function($http) {
$http({method:"GET", url:"/my/url"}).success(function(result){
return result;
});
});
In my controller I am using this service as:
function myFunction($scope, myService) {
$scope.data = myService;
console.log("data.name"+$scope.data.name);
}
Its working fine for me as per my requirements.
But the problem here is, when I reloaded in my webpage the service will gets called again and requests for server. If in between some other function executes which is dependent on the "defined service", It's giving the error like "something" is undefined. So I want to wait in my script till the service is loaded. How can I do that? Is there anyway do that in angularjs?
You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)
An example implementation would be like:
myApp.factory('myService', function($http) {
var getData = function() {
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:"/my/url"}).then(function(result){
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};
return { getData: getData };
});
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
// this is only run after getData() resolves
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
}
Edit: Regarding Sujoys comment that
What do I need to do so that myFuction() call won't return till .then() function finishes execution.
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
console.log("This will get printed before data.name inside then. And I don't want that.");
}
Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.
With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
I was having the same problem and none if these worked for me. Here is what did work though...
app.factory('myService', function($http) {
var data = function (value) {
return $http.get(value);
}
return { data: data }
});
and then the function that uses it is...
vm.search = function(value) {
var recieved_data = myService.data(value);
recieved_data.then(
function(fulfillment){
vm.tags = fulfillment.data;
}, function(){
console.log("Server did not send tag data.");
});
};
The service isn't that necessary but I think its a good practise for extensibility. Most of what you will need for one will for any other, especially when using APIs. Anyway I hope this was helpful.
FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put
myservice.$loaded().then(function() {$rootScope.myservice = myservice;});
and in the view I just did
ng-if="myservice" ng-init="somevar=myfunct()"
in the first/parent view element/wrapper so the controller can run everything inside
myfunct()
without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.

Resources