(Angularjs) How to $http.get data and store it in service - javascript

As you will see i'm new in AngularJS, JS and in web development at all =) really sorry for that but i try to.
I try to build a massive webform (about 200 different fields) with AngularJS controllers. I need access from controller to root data source. AngularJS team ask do not make Services just for storing data, but i want to make service for load and save data (at start into .json files on a server).
Service:
AppName.factory('MasterData', ['$rootScope', '$http', '$q', '$log',
function($rootScope, $http, $q, $log) {
var responseData;
$http.get('/getdata.php').then(function (response) {
responseData = response.data;
console.log(response.data);
});
return responseData;
}]);
Controller:
AppName.controller('justController', ['$scope', 'MasterData', '$log',
function ($scope, MasterData, $log) {
$scope.data = MasterData.justControllerSectionData;
console.log(MasterData);
}
]);
Controller return undefined. But console.log from service returns the object.
I feel that the problem is too easy, but i can't find how to solve it :(
Also i can't use function like .getData() from controller to service because it ask the data from server each time any controller loads. I have the routes in AngularJS app with 12-14 controllers (full webform divided by sections) and i think it is good to get the data from backend once.
P.S. I think there is problem with promises, but when i try to use code like this:
var defer = $q.defer();
$http.get('/getdata.php').success(function(data){
defer.resolve(data);
});
return defer;
I've got object with resolve, reject and so on. And really can't understand what can i do with it :(
Help me to get the data in controller :)

Your code doesn't work, because the callback you supplied to success() in your service is called asynchronously; after your service has returned, that is:
The sequence is like this:
The function in MasterData is run. The $http.get request is launched and attached the promise callback. responseData is referenced in this callback (aka. "closed over").
The function returns from the service to your controller. responseData has not been set yet, which doesn't stop the parent scope function from returning.
$http.get succeeds and responseData is set in the service however unreachable for the controller.
If the scoping of the nested function in success() is not clear to you, I'd recommend reading about closures in JavaScript (or even better, in general), for example here.
You can achieve your goal with a service like this:
function($q, $http, /* ... */) {
return {
getData: function() {
var defer = $q.defer();
$http.get('/getdata.php', { cache: 'true'})
.then(function(response) {
defer.resolve(response);
});
return defer.promise;
};
}
The $http service will happily cache your response data, so you don't have to. Note that you need to retrieve the promise from your deferred object to make this work.
The controller is like this:
/* omitted */ function($scope, YourService) {
YourService.getData().then(function(response) {
$scope.data = response.data;
});
}
Since success is depreciated, I modified success to then.

Services should return the promise rather than the data. This is the asynchronous way.
First fetch the value in the Angular's run method. For this example I put it in the $rootScope since that makes it accessible to all scopes in all controllers.
AppName.run(['$http', '$rootScope',
function($http, $rootScope) {
console.log('Run');
$http.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo')
.success(function(data) {
$rootScope.resource = data;
console.log($rootScope.resource);
});
}
])
This is not really necessary unless you store it in some weird place.
AppName.service('Resource',['$rootScope',
function($rootScope) {
return $rootScope.resource;
}
]);
Every scope will inherit the values in the $rootScope (thats why the service really isn't necessary.
AppName.controller('mainController', ['$scope', 'Resource',
function($scope, Resource) {
console.log('controller');
console.log(Resource);
}
]);
Warning!!! This value will not be available until after the first controller loads. If you use it in the controller just remember that you can bind it to html but the first pass through the controller code will not have initialized the variable yet.

Related

Calling $http promise inside controller

Thanks in advance for the help...
I have a controller I'm using to call an API to send a password reset link. I have abstracted the actual $http call off into a service to keep the controller thin. Originally I was doing something like this:
angular.module('module')
.service('forgotPasswordService', ['$http', function($http) {
$http(request).then(function() {
return {}; //return some object using response
}]);
I felt like this would be the best approach as it would keep the controller as thin as possible and kept all service related actions separate. My problem with this was that returning from within the promise never actually returned me anything. I had to actually return the $http service call to get the promise. The only way I was able to make all of this work was if I called .then from within the controller.
//controller
angular.module('module')
.controller('forgotPasswordCtrl', ['forgotPasswordService', function(forgotPasswordService) {
forgotPasswordService.forgotPassword(emailAddress).then(function() {
//do stuff
}
}]);
//service
angular.module('module')
.service('forgotPasswordService', ['$http', function($http){
this.forgotPassword = function(emailAddress) {
return $http(request);
};
}]);
This just feels a little wrong to me because the controller now depends on receiving a promise back from the service. I may just be overthinking this but I would like a second opinion.
Is this considered acceptable/good practice? Is there an alternative to this which would allow me to achieve the encapsulation I'm looking for?
Thanks again.
I've interfaced with the $http from the controller in two slightly different ways.
Like you it felt wrong returning the $http from the service and interfacing with it.
So first I created services and passed in a success method and an error method (callbacks).
// Service
angular.module('module')
.service('forgotPasswordService', ['$http', function($http) {
function sendForgotPasswordEmail(emailAddress, success, error){
$http.post('/api/v1/resetpassword', {emailAddress:emailAddress})
.then(success, error);
}
return {
sendForgotPasswordEmail: sendForgotPasswordEmail
}
}]);
// Controller
angular.module('module')
.controller('forgotPasswordCtrl', ['forgotPasswordService', function(forgotPasswordService) {
forgotPasswordService.sendForgotPasswordEmail(emailAddress,
function(response){ //success
// notify user of success
},
function(response){ // error
// notify user of error
});
}]);
This worked great. I created an large application this way, but as I started on my second large angular project I wondered why I was hiding the $http's promise?
By passing back the promise, I can use other libraries that support promises. With my first approach I can't leverage other libraries promise support.
Passing back the $http promise
// Service
angular.module('module')
.service('forgotPasswordService', ['$http', function($http) {
function sendForgotPasswordEmail(emailAddress){
return $http.post('/api/v1/resetpassword', {emailAddress:emailAddress});
}
return {
sendForgotPasswordEmail: sendForgotPasswordEmail
}
}]);
// Controller
angular.module('module')
.controller('forgotPasswordCtrl', ['forgotPasswordService', function(forgotPasswordService) {
forgotPasswordService.sendForgotPasswordEmail(emailAddress)
.then(
function(response){ //success
// notify user of success
},
function(response){ // error
// notify user of error
});
}]);
I deleted my original answer, and I feel like a dork for stating that you could do it the other way. When I went back and checked my original code back when I first started angular, I found that I was calling then() twice in my application - once in my service where I returned the data, and once in my controller because calling $http(request).then() returns a promise.
The fact is, you're dealing with an asynchronous call. Suppose in your controller, you wanted to do this:
$scope.foo = myService.getFoo(); // No then()
The XmlHttpRequest inside the $http in getFoo() is an asynchronous call, meaning that it calls it and moves on. The synchronous option is deprecated. It's bad practice to make a blocking synchronous HTTP call because it will seize up your UI. This means you should use a callback when the data is ready, and the promise API is made just for that.
If you absolutely do not want to use the then() in your controller, I suppose you could probably pass your scope binding parameters to your service and let your service update them in your then call. I haven't tried this, and because it's asynchronous, I'm not sure if angular will know to call a digest() so you may need to call a $scope.$apply() if the values don't update. I don't like this, because I think the control of the values in the scope should be handled by the controller and not the service, but again - it's your personal preference.
Sorry for leading you astray with my initial answer - I ran into the same question you had, but when I looked back - I saw I used a silly solution.
-- Relevant statements in original answer --
Consider the following:
Where do you want your error handling for the call and who needs to know about it?
Do you need to handle specific failures in a particular controller or can they all be grouped together to one error handler? For some apps, I like to display the errors in a particular place rather than in a general modal dialog, but it's acceptable to create a service to handle all errors and pop them up for the user.
Where do you want to handle your progress/busy indicator?
If you have an interceptor wired up for all http calls and broadcasting an event to show/hide the busy indicator, then you don't need to worry about handling the promise in the controller. However some directives will use the promise to show a busy indicator which requires you to bind it to the scope in the controller.
To me, the decision is determined by the requirements and by personal choice.
Try using a callback like so:
angular.module('module')
.service('forgotPasswordService', ['$http', function($http) {
var recovery = function(request, callback) {
$http(request).then(function(response) {
callback(response);
})
}
return { recovery: recovery }
}]);
Then you would call it like this:
forgotPasswordService.recovery('http://...', function(response){
console.log(response);
})

AngularJS get dashboard settings using $htttp before initializing a dashboard controller

So I am still on a crash course with Angular. I am working on quite a complicated dashboard framework, all written in angular. Before I load the controllers, I need to get a bunch of dashboard settings from the server first using $HTTP. These settings are then used to control the layout of the dashboards.
So I read the way angular builds is by first running config methods, then run methods, then the controllers.
I can't use $HTTP in a config method, so I have built this in my main.js:
MetronicApp.run(['$rootScope','$http', function($rootScope,$http) {
var CUID = Cookies("CUID");
console.log('portlet settings for '+ CUID);
$http.get('/myurl/V3_portlet_settings?p_user_id='+CUID)
.then(function(response) {
console.log(response.data);
console.log('portlet status: ' + response.status);
$rootScope.$broadcast("dashSettings",response.data);
});
}]);
When I run, this all works happily and I see the data in the console.
Then in my controller:
$scope.$on( "dashSettings",
function(event,data){
$scope.dData = data;
console.log('dash data service identified in dash controller');
console.log($scope.dData.count);
} );
Couple of questions:
Is this the best way to get settings before initializing the dash. My plan would be to embed the calls that build the dash inside my $scope.$on block. I started looking at how to run a run method synchronously before the controllers initialize, but maybe I don't need to.
Any obvious idea why the $scope.$on method does not seem to fire?
Thanks in advance
A different approach would be to place your $http functions in a service or factory and then resolve these in your controller.
The key here is the use of promise. Angular documentation describes this as
A service that helps you run functions asynchronously, and use their
return values (or exceptions) when they are done processing
First create a service:
app.factory('DataService', function($http) {
var getValues= function() {
var url = '/myurl/V3_portlet_settings?p_user_id='+ CUID;
return $http.jsonp(url) // returns a promise
};
return {
getValues: getValues
}
});
And then in your controller:
myApp.controller('MyController', function ($scope, DataService) {
DataService.getValues().then( // resolve the promise using .then()
function(data){
// successcallback
// you can now safely populate the data in you controller
console.log(data);
},
function(error){
// errorcallback
console.log(error);
})
});
I think it is a better approach to use data services to handle data operations such as $http requests.
The return of promises allows for chaining of (multiple) promises and better handling of async calls.
You might find John Papa's style guide useful, especially the section about 'Separate Data Calls' (Y060) and 'Return a Promise from Data Calls' (Y061)

Injecting $http service into $http interceptor?

I have the following interceptor:
var interceptor = ['$http', '$q', function ($http, $q) {
//...
}];
This generates a circular dependency, because $http will depend on this interceptor, and this interceptor will depend on $http.
I want to get the $http service because I intend to refresh some authorization tokens of the user if I get a 401 Unauthorized response.
For this, I have to call my OAuth endpoint and retrieve the new tokens.
How can I inject this service into my interceptor?
I also tried the following alternative:
var interceptor = ['$injector', '$q', function ($injector, $q) {
var $http = $injector.get('$http');
}]
But I'm getting the same error.
Is this possible?
I don't want to use the jQuery library and I want my application to be pure AngularJS, so $.ajax(...) answers are not useful to me.
Even the second snippet causes cdep error because interceptor service will get instantiated and in the constructor you are trying to get $http in the process, which causes cdep error. You would need to get the http service (or any of your service that injects http) later, after interceptor service has been instantiated. You could easily get it from $injector on demand when you need it, example on a reponseError.
var interceptor = ['$injector', '$q',
function($injector, $q) {
return {
responseError: function(rejection) {
//Get it on demand or cache it to another variable once you get it. But you dont really need to do that you could get from the injector itself since it is not expensive as service is a singleton.
var $http = $injector.get('$http');
//Do something with $http
return $q.reject(rejection);
}
}
}
]
try wrapping your injector code with in anonymous function
var interceptor = ['$injector', '$q', function ($injector, $q) {
return function(){
var $http = $injector.get('$http');
}
}];

AngularJS - Wait to Load data to display the view

I am really new to AngularJS and after reading several questions and some articles I am a little confused about the correct way to load data and wait till its loaded to display the view.
My controller looks like this
app.controller('ResultsController', ['$scope','$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.poll = {};
$scope.$on('$routeChangeSuccess', function() {
showLoader();
$http.get("rest/visualizacion/" + $routeParams.id)
.success(function(data) {
$scope.poll = data;
hideLoader();
})
.error(function(data) {
// Handle error
});
});
}]);
I have seen there are people who create a service for $http calls, is it necessary? Why is it better?
The appropriate way to do that is to use the resolve property of the route. From the documentation:
resolve - {Object.<string, function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
key – {string}: a name of a dependency to be injected into the controller.
factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.
So, if you want poneys to be retrieved from the backend before the router goes to the poney list page, you would have
resolve: {
poneys: function($http) {
return $http.get('/api/poneys').then(function(response) {
return response.data;
)};
}
}
And your controller would be defined as
app.controller('PoneyListCtrl", function($scope, poneys) {
$scope.poneys = poneys;
// ...
});
Of course, you could also put the code making the $http call and returning a list of poneys in a service, and use that service in the resolve.

One time async data load in angular factory - convention ?

I'm writing a simple app for displaying (read-only) employee information. I would like to load the info from JSON once only. Not sure what the convention is around this in the angular factory.
I know that one solution is to but the JSON file in a javascript file and load it as a js file (but I would want to keep the file as JSON).
I guess I could also wrap the http call in a promise, and change the return accordingly.
Is there a way of doing this without changing the return? Block on the employee load ?
.factory('Employees', ['$http', function($http) {
var employees = $http.get('res/employees.json').then(function(response){
return response.data; // This is async so won't return right away
});
// This way works (since not async)
// var employees = [
// {
// "id": 232,
// "name": "Bob"
// }];
return {
all: function() {
return employees; // This will return empty before employees is loaded
}
}
}]);
This is a wrong implementation of the promise pattern. Your 'employee' service should return a promise also that gets initialized and then returns the same resolved promise upon subsequent requests. Something like this:
.factory('Employees', ['$q', '$http', function($q, $http) {
var _deferred = $q.defer();
$http.get('res/employees.json')
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
_deferred.resolve(data);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
_deferred.reject("Error");
});
};
return {
getEmployees: function(){
return _deferred.promise;
}
}
}]);
.controller('MyController', ['$scope', 'Employees', function($scope, Employees) {
$scope.employees = [];
$scope.employees = Employees.getEmployees();
}]);
$scope.employees will initially be an empty array until the promise is resolved. Also, this code does not have error recovery.
One possible solution that might work for you is to fetch the data and manually bootstrap your application with an appended value or service of the fetched data. There are already built solutions for this kind of problem, one is called the angular-deferred-bootstrap and another is a solution I made just a month ago. Both are making use of the AngularJS lifecycle in manually bootstrapping the application, using angular.bootstrap(). Note that when you are manually bootstrapping your application you need to remove the ng-app directive.

Categories