0

Following is my $routeProvider code -

  $routeProvider
    .when("/login", {
      template: JST["app/templates/login"],
      controller: "LoginController",
    })
    .when("/dashboard", {
      template: JST["app/templates/dashboard"],
      controller: "DashboardController",
      resolve:{
        getUser: function(UserService) {
          return UserService.chkUser()
        }
      }
    })
    .otherwise({ redirectTo: function() {window.location = "/login";} });

    $locationProvider.html5Mode(true);
});

Following is my UserService code -

angular.module("app").factory("UserService", function($http, $q, User) {
  return {
    chkUser: function() {
      var defer = $q.defer();

      defer.resolve(false);
      return defer.promise;
      // Also tried -
      // window.location = "/login";
    }
  };
});

Problem -

Now when I am navigating to http://example.com/dashboard in a browser I was expected to be logged back at "/login" but I am not, let me know what I am wrong about the resolve usage in angularJS.

Trialcoder
  • 5,816
  • 9
  • 44
  • 66

1 Answers1

1

Well, your resolve work fine and if you inject getUser into DashboardController, it's value should be false. Because you immediately resolve the promise with false value.

Try something like this:

angular.module("app").factory("UserService", function($http, $q, User, $location) {
  return {
    chkUser: function() {
      var defer = $q.defer();
      $http(...., function(user){
         if(user){
            defer.resolve(user);
         }else{
            defer.reject();
            $location.path('/login');
         }
      });
      return defer.promise;
    }
  };
});

Or create a fiddle reproducing the problem, so we could have a look and touch that one.

gorpacrate
  • 5,109
  • 3
  • 21
  • 18
  • It's just a variable name taken from your code. You are resolving it in your dashboard route: `.when("/dashboard", {..., resolve:{ getUser: ...}}` – gorpacrate Aug 25 '14 at 12:26
  • You will get it's resolved value in your route's controller if you inject it into controller: `angular.module('app').controller('DashboardController, function($scope, getUser){ console.log(getUser); });` – gorpacrate Aug 25 '14 at 12:31
  • ohh my bad :( Lost in the angular way :) Let me try this – Trialcoder Aug 25 '14 at 12:31