Search code examples
angularjsangularjs-http

Why promise doesnt work as expected in AngularJS


In my AngularJS application on every request to change the page i run :

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        var user;
        $http.get('/api/Authentication/UserAuthenticated').then(function (data) {
        console.log("call");
         user = data.data;
       });   
      console.log("end of call");
    });

When i run application and test what is happening i see in console that "end of call" is returned before console.log("call"); which means that user is not set. Which means that if i want to check if user is logged in on change of route user will be undefined.

How do i make Angular run-> http request and only then keep going?


Solution

  • I misunderstood the question a bit. You can let the $routeProvider resolve the $http promise:

    var app = angular.module("myApp");
    
    app.config(["$routeProvider", function($routeProvider) {
      $routeProvider.when("/",{
        templateUrl: "myTemplate.html",
        controller: "MyCtrl",
        resolve: {
          user: ["$http", "$q", function($http, $q) {
            var deferred = $q.defer();
            $http.get('/api/Authentication/UserAuthenticated').success(function(data){
               deferred.resolve(data.data);
            }).error(function(error) {
               deferred.resolve(false);
            });
            return deferred.promise;
          }]
        }
      });
    }]);
    

    If the code to fetch the user data is too complex, you could create a service for it, and inject that service in the $routeProvider's resolve function.

    In your controller, you just inject the promise (which will be resolved):

    app.controller("MyCtrl",["$scope","user", function($scope, user) {
       if (!user) {
          alert("User not found");
       }
    ...
    }]);