AngularJS - Wait to Load data to display the view - javascript

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.

Related

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)

Ui-router loads state, then how can I run a function?

I'm new to Angular and states and wrapping my head around ui-router. I've been doing it with jQuery for too long. In jQuery, I can load up something with ajax, then on the success, perhaps run another function. How do you do that with Angular?
For example, I have the following
var ivApp = angular.module('ivApp', ['ui.router']);
ivApp.config(function($urlRouterProvider, $stateProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'partials/partial-home.html'
})
});
Which simply loads up partial-home.html into my ui-view. But how to tell it to run a function once that is done? For example, I have authenticate.js and a function authenticate(). How do I run authenticate() once 'home' state has loaded?
Additionally, can I tell angular to only load authenticate.js for this state? Or should I have already loaded it in the template. I know that if I include the script in partial-home.html (e.g. <script src="authenticate.js"></script>) chrome throws me an error about synchronous xmlhttprest being deprecated. So somhow in the config, can I declare authenticat.js as a dependency of the state or something like that?
At the moment I have worked out I can do something like:
ivApp.controller('authenticate', function($scope) {
// start authorisation
authenticate();
});
And then define the controller authenticate in my ui-router states. But is that how it's done? It works basically. My authenticate function is doing things like changing things in the DOM, but I read controllers shouldn't be used for this.
Thanks for any pointers
Let's break down into parts.
If you just want to load authenticate.js in this particular home state, use ocLazyLoad. It's one of the best way to load a resource lazily. And it works really well if ui-router too!
$stateProvider.state('index', {
url: "/", // root route
views: {
"lazyLoadView": {
controller: 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
templateUrl: 'partial-home.html'
}
},
resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load('js/authenticate.js');
}]
}
});
If you want to run authenticate() once the state is loaded, there are quite a number of ways to do it. One way of course is listening to the $stateChangeSuccess event, but I would avoid using it since you know, global variables, and global variables are bad. I do not want to pollute my $rootScope just because I have a really specific use case.
You can use resolve in ui-router too. Resolve is executed after the state is loaded and before the controller is instantiated. I would recommend to use this method as you can chain your promises together with ocLazyLoad, if you are using it (which you should).
Manipulating DOMs after a state is loaded? Sure, that's what templateUrl for! Design your template such that it accomadates to your authenticate() functions. If you combine it with resolve, there isn't really much of a problem separating concerns as you would already have executed authenticate() before controller is loaded.
Edit: Adding in Plnkr
You want to first lazily-load authenticate.js, and then use the function inside authenticate.js to do something. Since resolve in ui.router executes promise chains in parallel, we have to chain them up, i.e, load your jsfiles first, and then return your status of authentication.
We need to declare a deferred promise using $q service. We then return this promise in the resolve, so that you controller is listening to one promise instead of two. Here is how:
$stateProvider
.state('Home', {
templateUrl: 'home.html',
controller: 'homeCtrl',
resolve: {
//need to chain our promises since we neeed to first load the authenticate.js
//and second, execute authenticate()
loadJsAndAuth: ['$ocLazyLoad', '$q', '$injector', function($ocLazyLoad, $q, $injector) {
//declare a deferred promise
var deferred = $q.defer();
//now load the authenticate.js
$ocLazyLoad.load('authenticate.js').then(
//load successful! proceed to use our authenticate function!
function(success) {
//since we already have loaded authenticatejs, now we can inject the service and use it
var authSvc = $injector.get('authenticateSvc');
//this is just a demo on how to authenticate.
//change this to banana to see the authenticate fail
var fruits = 'apple'
if (authSvc.authenticate(fruits)) {
//authenticate pass, resolve the promise!
deferred.resolve('authenticated!');
}
//authenticate fail, reject the promise
deferred.reject('authenticate failed');
},
//load of jsfiles failed! reject the promise.
function(error) {
deferred.reject('Cannot load authenticate.js')
})
return deferred.promise;
}]
}
})
And in your controller, you can get the resolved promises!
//you can get access to what is is being resolved by loadJsAndAuth
.controller('homeCtrl', ['$scope', 'loadJsAndAuth', function($scope, loadJsAndAuth) {
$scope.status = loadJsAndAuth // this is resolved promises.
}]);

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.

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

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.

AngularJS - Initialize services before controller

I am trying to initialize my applications services before the controller starts running.
I would have thought that i could achieve this by resolving a promise-returning function first:
va.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: '../partials/home.php', controller: 'VaCtrl',resolve: {
pp: vac.loadData
}});
}]);
var vac = va.controller('VaCtrl',function($scope,$http,$q,packingProvider){
console.dir(packingProvider.data[2]);
});
vac.loadData = function($http,$timeout,$q,packingProvider){
$http.post('../sys/core/fetchPacking.php').then(function(promise){
packingProvider.data = promise.data;
});
var defer = $q.defer();
$timeout(function(){
defer.resolve();
},2000);
return defer.promise;
};
However, the controller is still loaded before the promise has beenr esolved, resulting in the console yelling
Cannot read property '2' of undefined
at me.
What am i doing wrong?
Edit:
Also, the controller seems to get invoked twice, first time with the undefined pacingProvider.data object, and 2 secons later with everything fine.
Instead of using the promise returned by $timeout, you could directly use the promise
returned by $http.
Rewrite your loadData fn this way -
vac.loadData = function($http,$timeout,$q,packingProvider){
var promise = $http.post('../sys/core/fetchPacking.php').then(function(promise){
packingProvider.data = promise.data;
});
return promise;
};
Read the first line in the General Usage section here - $http promise
Also, resolve is a map of dependencies.
resolve - {Object.=} - 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.
Hence, Angular will automatically expose the map for injection. So, you can do this -
var vac = va.controller('VaCtrl', function($scope, pp){
// 'pp' is the name of the value in the resolve map for $routeProvider.
console.dir(pp[2]);
});
NOTE: although this will solve your problem, this answer is probably the right solution.
Services are always initialized before controllers. The problem, as you stated, is that your promise hasn't resulted yet. The best option for that is to stick to the promises.
Instead of exposing the data object, expose the promise and use it:
vac.loadData = function($http,$timeout,$q,packingProvider){
packingProvider.data = $http.post('../sys/core/fetchPacking.php');
return packingProvider.data;
};
And in your controller, always attached to the promise, after the first resolval, it will get resolved in the next tick:
var vac = va.controller('VaCtrl',function($scope,$http,$q,packingProvider){
packingProvider.data.then(function(value) {
console.dir(value[2]);
});
});

Categories