【问题标题】:UI-Router: change template on missing statesUI-Router:更改缺失状态的模板
【发布时间】:2014-11-02 04:50:55
【问题描述】:

当用户访问缺失状态时,是否可以“设置”视图?我希望 404 处理程序仅在用户尝试访问不存在的页面而不是重定向用户时发出一些通知。

类似于Github's 404

【问题讨论】:

  • 使用otherwise。这是另一个帖子的链接:stackoverflow.com/questions/23281351/…
  • 我想我找到了答案。会尝试,如果没有人回答我的问题。
  • 如果缺少状态,我们不能更改属于状态的模板。我们真的需要导航到otherwise def...哪里应该是状态,哪里应该是正确的模板。检查this

标签: angularjs angular-ui-router


【解决方案1】:

您可以在 app.run 函数中检查状态更改事件。 像这样..

app.run(function ($rootScope, $state) {
  $rootScope.$on("$stateNotFound", function (event, unfoundState, fromState, fromParams) {
        //manage state not found
  });
});

来源:https://github.com/angular-ui/ui-router/wiki

【讨论】:

    【解决方案2】:

    正如@cshion 所说,您可以抓住$stateNotFound 并转到另一个状态 或者你想要的东西。

    app.run(['$rootScope', '$state', function ($rootScope, $state) {
      $rootScope.$on("$stateNotFound", function (event, unfoundState, fromState, fromParams) {
            $state.go('my404state');
      });
    }]);
    

    这只能通过调用$state.go('missingstate'); 起作用但是如果用户输入一个虚假的url 则不起作用。所以更适合测试/调试目的。

    另一方面,您可以使用 $urlRouterProvider.otherwise 重定向用户

    app.config( ['$stateProvider', '$urlRouterProvider',
       function ($stateProvider,   $urlRouterProvider) {
           $urlRouterProvider
               .when('/', [$state, function($state) { $state.go('home') }])
               .otherwise('/notfound');
        }
    ]);
    

    并创建一个特定的状态来显示 404 not found。

    编辑:基于 cmets。

    另一种选择是使用$urlRouterProvider.rule 进行自定义网址处理

    app.config(['$urlRouteProvider','MyAuthService', function ($urlRouterProvider) {
      
       $urlRouterProvider
             .when('/', [$state, function($state) { $state.go('home') }])
             .rule(function ($injector, $location) {
                   if (MyAuthService.isAuthenticated()) {
                       return "/user/mainpage";
                   }
                   return $location.path();
              })
             .otherwise('/notfound');
    }])
    

    Note that otherwise wraps a rule that returns the same url that receive.

    【讨论】:

    • 其实我是用这种方法的,但是当我们管理经过身份验证的用户时会发生什么,如果输入一个虚假的 url,更好的选择是重定向到用户的主页,所以在这种情况下,我们需要管理我认为 app.run 中的虚假状态(或位置)。
    • $state.go 是否更改 URL/位置 ($window.location)?
    • 是的,$state.go()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2016-06-03
    • 2015-02-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多