I need to perform an AJAX request against my API for authentication information before routing kicks in and routing data requests resolve (I'm using a server-to-server OpenID auth solution).
I initialize my app like this currently:
angular.module('mynamespace.admin', [
'ngRoute',
'ui.bootstrap',
'mynamespace.directives',
'mynamespace.filters',
'mynamespace.factories',
'mynamespace.resources',
'mynamespace.admin.templates',
'mynamespace.admin.forms'
]);
angular.module('mynamespace.admin').run(['$rootScope', '$http', 'base64', function($rootScope, $http, base64) {
if (!window.location.origin) {
window.location.origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
// I NEED THIS TO FINISH BEFORE ROUTES RUN AND PERFORM
// HTTP REQUESTS TO RESOLVE DATA
$http.get(window.location.origin + '/account').success(function(accountData) {
$rootScope.accountData = accountData;
// Set up auth headers to be sent with every HTTP request.
$http.defaults.headers.common = { 'Access-Control-Request-Headers': 'accept, origin, authorization' };
$http.defaults.headers.common['Authorization'] = 'Basic ' + base64.encode(accountData.apiKey + ':' + accountData.apiPassword);
});
}]);
angular.module('mynamespace.admin').config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', { // THIS IS RUNNING BEFORE THE $http REQUEST in .run() finishes
redirectTo: '/forms'
});
}]);
Routing kicks in at the .config() callback at the end. Unfortunately the /forms route contains routes with resolve items which end up making $http requests before I set up the common $http headers inside the .run() callback. Basically I have a race condition.
So, my question is: How can I execute and complete an AJAX request and ensure it returns BEFORE my app's routing kicks in and routes start making AJAX requests?
If this question is somehow unclear, I ask that you please request clarification, and I will clarify.
Use routeChangeStart event of angular.
var checkAuthentication = function(event, routeChange) {
routeChange.$$route.resolve = {
app: function($q) {
var deferred = $q.defer();
//Authentication({deferred.resolve();})
return deferred.promise;
}
}
}
$rootScope.$on('$routeChangeStart', checkAuthenticationFn);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments