【问题标题】:Redirect user to home page if type not existing url如果输入的 URL 不存在,则将用户重定向到主页
【发布时间】:2016-12-06 08:12:45
【问题描述】:

如果用户类型不存在,我需要将“登录”用户重定向到主页。我有一个名为“authService”的服务,我可以在其中检查是user auth == true 还是false

如果用户未经过身份验证 (authService.auth == false),我使用 $STATE.GO 重定向到登录页面。

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider) {
 $urlRouterProvider.otherwise(function ($injector, $location) {

        var $state = $injector.get("$state");
        $state.go("login");
    });
}]);

现在我想做类似的重定向用户到主页,当用户是auth == true。当用户使用令牌时,尝试输入不存在的 url,重定向到主页。

我尝试通过注入 authService 服务并制作 if/else 来做到这一点。 但这不起作用,因为我收到错误

错误:$injector:unpr 未知提供者 未知提供者:authService

 app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', 'authService',
function ($stateProvider, $urlRouterProvider, $locationProvider, authService) {
 if (authService.auth == false) {
    $urlRouterProvider.otherwise(function ($injector, $location) {

        var $state = $injector.get("$state");
        $state.go("login");
    });
    }
else {
   $urlRouterProvider.otherwise(function ($injector, $location) {

        var $state = $injector.get("$state");
        $state.go("home");
    });

 }
}]);

这是不好的解决方案吗?我可以将自定义服务注入 app.config 吗?有人可以帮我吗?

谢谢。

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    您应该在 run 函数上执行此操作并使用 $stateChange 事件:

    app.run(['$state', '$rootScope', 'authService', function($state, $rootScope, authService) {
        $rootScope.$on("$stateChangeStart", function(event, toState) {
            if (toState.name !== "home" && !authService.auth) {
                // Prevent going to the state
                event.preventDefault();
                $state.go("home");
            });
        });
    }]);
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 2017-08-11
      • 2011-10-25
      • 2011-10-25
      • 2015-06-11
      • 2016-08-16
      • 2019-05-05
      • 2012-01-27
      相关资源
      最近更新 更多