通过RouteProvider将部分转发解析到另一个视图

时间:2014-08-05 15:12:58

标签: angularjs redirect

我在AngularJS中遇到了提供程序的问题。 我想在任何视图中检查用户是否已登录。如果没有,那么它应该重定向到/ login。在控制台上,没有错误。我不知道出了什么问题。

var app= angular.module("app", ["ngRoute", "ngAnimate", "ngResource"]);

app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
    var getItemNameById = function($route, $location, service, breadcrumbs, path) {
        service.getItem($route.current.params.id).then(function(evt) {
            if(evt.title) {
                $route.routes[path].label = evt.title;
            } else if(evt.name) {
                $route.routes[path].label = evt.name;
            }
            breadcrumbs.generateBreadcrumbs();
        }, function() {
            $location.path("/404");
        });
    };

    $routeProvider
        .when("/", {
            template: "",
            label: "Home",
            resolve: function($q, $location) {
                   alert("in resolve Home...");
                   var deferred = $q.defer(); 

                   if (!isLoggedIn) {
                        $location.path('/login');
                   }
                   deferred.resolve();
                   return deferred.promise;
            }
        })
        .when("/patient", {
            templateUrl: "patient.html",
            label: "Patient",
            resolve: function($q, $location) {
                   alert("in resolve Patient...");
                   var deferred = $q.defer(); 

                   if (!isLoggedIn) {
                        $location.path('/login');
                   }
                   deferred.resolve();
                   return deferred.promise;
            }
        })
        .when("/doctor", {
            templateUrl: "doctor.html",
            controller: "DoctorController",
            label: "Doctor",
            resolve: function($q, $location) {
                   alert("in resolve Home...");
                   var deferred = $q.defer(); 

                   if (!isLoggedIn) {
                        $location.path('/login');
                   }
                   deferred.resolve();
                   return deferred.promise;
            }
        });
}]);

app.run(["$rootScope", "LoginService", function($rootScope, LoginService) {
    LoginService.checkSession().then(function(response) {
        $rootScope.isLoggedIn = response;
    }, function(reject) {
        $rootScope.isLoggedIn = reject;
    });

}]);

为什么不在主页上输入部分解析(警报也不显示)?

最好的问候

1 个答案:

答案 0 :(得分:0)

我认为你应该设置一个路由变更的事件,如下所示:

    app.run(function($rootScope) {
     $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
      if (nextRoute != null ) {
         //Check session 
      }   
    });
   });