Angular:如何处理HTML5模式路由和哈希路由?

时间:2016-11-11 00:30:45

标签: javascript angularjs html5

我一直在使用"标准" Angular 1中使用#符号的路由(例如/app#/home)。现在我想切换到HTML5模式以获得漂亮的URL(例如:/app/home)。

我已经用$locationProvider.html5Mode(true)切换了HTML5模式,一切都按预期工作。

但是,我们的一些用户可能仍然在电子邮件中有书签和链接,这些书签和链接具有旧的URL格式,而且会破坏。我希望旧网址仍然有用(让/app#/home自动重定向到/app/home。)

我尝试过使用默认路由来查看哈希值,如下所示:

$routeProvider
    .when({ ... })
    .otherwise({
        'controller': function($location) {
            var hash = $location.hash();
            // At this point the hash is undefined (even when there is one in the URL)
            console.log('hash = ' + hash);
//            if (hash && hash.indexOf('/') == 0) {
//                $location.path(hash);
//            } else {
//                $location.path('/home')
//            }
        }
    });

遗憾的是没有用(控制器没有看到散列,而Angular似乎进入无限的摘要循环)。

关于如何实现这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

使用$ routeChangeStart:

 angular.module('routing', ['ngRoute'])
       .run(['$rootScope', '$location', '$window', function($rootScope, $location, $window) {
          $rootScope.$on("$routeChangeStart", 
            (event, current, previous, rejection) => {
              if (/#\//.test($window.location.hash)) {
                 $location.path($window.location.hash.replace('#', ''));
              }
          });

...
相关问题