【问题标题】:AngularJS - redirect to another pageAngularJS - 重定向到另一个页面
【发布时间】:2014-08-04 17:32:21
【问题描述】:

我学习了 AngularJS,但在重定向页面时遇到了问题。

用例:

  • 我有一个 index.html 主页,但如果用户没有登录,那么它应该重定向到 login.html 页面(每个页面也应该只有登录用户可以访问)

在主 app.js 中,我有一个提供者和运行者:

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

app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {

$routeProvider
        .when("/", {
            template: "index.html"
        })
        .when("/other", {
            templateUrl: "other.html"
        });
}]);


app.run(["$rootScope", "LoginService", function($rootScope, LoginService, $window) {
    LoginService.checkSession().then(function(response) {
        $rootScope.isLoggedIn = response;
            if ($rootScope.isLoggedIn === false) {
                console.log('DENY');
                $window.location.href = '/login';
            }
    }, function(reject) {
        $rootScope.isLoggedIn = reject;
    });
}]);

问题: 当我没有登录时,当涉及到“$window.location.href ='/login'”这一行时,这是控制台中的错误:

DENY 
TypeError: Cannot read property 'location' of undefined
    at LoginService.checkSession.then.$rootScope.isLoggedIn 

当我在该行之前设置调试器时,它会打印:

$window
undefined

我不知道为什么会这样。有人可以帮我解决这个问题吗?

最好的问候, 卢克

【问题讨论】:

    标签: angularjs redirect


    【解决方案1】:

    您忘记将$window 作为“注入数组”中的字符串注入:

    ["$rootScope", "LoginService","$window", function($rootScope, LoginService, $window)
    

    【讨论】:

      【解决方案2】:

      当您定义 app.run 时,您不会为依赖注入传递 $window。

         app.run(["$rootScope", "LoginService", function($rootScope, LoginService, $window)
      

      尝试用这个替换上面的行

      app.run(["$rootScope", "LoginService","$window", function($rootScope, LoginService, $window)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-12
        • 1970-01-01
        • 2016-12-14
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 2016-06-10
        相关资源
        最近更新 更多