Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$http request before AngularJS app initialises?

In order to determine if a user's session is authenticated, I need to make a $http request to the server before the first route is loaded. Before each route is loaded, an authentication service checks the status of the user and the access level required by the route, and if the user isn't authenticated for that route, it redirects to a login page. When the app is first loaded however, it has no knowledge of the user, so even if they have an authenticated session it will always redirect to the login page. So to fix this I'm trying to make a request to the server for the users status as a part of the app initialisation. The issue is that obviously $http calls are asynchronous, so how would I stop the app running until the request has finished?

I'm very new to Angular and front-end development in general, so my issue maybe a misunderstanding of javascript rather than of Angular.

like image 445
Ben Davis Avatar asked Oct 29 '13 09:10

Ben Davis


2 Answers

You could accomplish that by using resolve in your routingProvider.

This allows you to wait for some promises to be resolved before the controller will be initiated.

Quote from the docs:

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. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired.

Simple example

    app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
            myVar: function($q,$http){
                var deffered = $q.defer();

                    // make your http request here and resolve its promise

                     $http.get('http://example.com/foobar')
                         .then(function(result){
                             deffered.resolve(result);
                          })

                return deffered.promise;
            }
        }}).
        otherwise({redirectTo: '/'});
}]);

myVar will then be injected to your controller, containing the promise data.

Avoiding additional DI parameter

You could also avoid the additional DI parameter by returning a service you were going to inject anyways:

app.config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
                myService: function($q,$http,myService){
                  var deffered = $q.defer();

                      /*  make your http request here
                      *   then, resolve the deffered's promise with your service.
                      */

                  deffered.resolve(myService),

                  return deffered.promise;
                }
            }}).
            otherwise({redirectTo: '/'});
    }]);

Obviously, you will have to store the result from your request anywhere in a shared service when doing things like that.


Have a look at Angular Docs / routeProvider

I have learned most of that stuff from that guy at egghead.io

like image 116
Wottensprels Avatar answered Nov 11 '22 19:11

Wottensprels


Encapsulate all your resources with a sessionCreator and return a promise. After resolve then to your controller so you can keep it free of specific promise code.

app.factory('sessionCreator', ['$http', '$q', 'urlApi',

  function ($http, $q, urlApi) {
    var deferred = $q.defer();

    $http.get(urlApi + '/startPoint').success(function(data) {
      // Do what you have to do for initialization.
      deferred.resolve();
    });

    return deferred.promise;
  }

]);

app.factory('Product', ['$resource', 'urlApi', 'sessionCreator',

  function($resource, urlApi, sessionCreator) {
    // encapsulate all yours services with `sessionCreator`
    return sessionCreator.then(function() {
      return $resource(urlApi + '/products', {}, {
        query: {method:'GET', params:{}, isArray: true}
      });
    });
  }

]);

app.config(['$routeProvider', function ($routeProvider) {

  var access = routingConfig.accessLevels;

  $routeProvider
    .when('/product', {
      templateUrl: 'views/products.html', controller: 'ProductCtrl',
      // resolve then in router configuration so you don't have to call `then()` inside your controllers
      resolve: { Product: ['Product', function(Product) { return Product; }] }
    })
    .otherwise({ redirectTo: '/' });
}]);
like image 45
armoucar Avatar answered Nov 11 '22 18:11

armoucar