Angular路由 - 如何重定向到外部网站?

10

在 AngularJS 路由文件中,有一个 otherwise 路由选项,可以替换 404 错误页面:

$routeProvider
.when(...)
.otherwise({
    redirectTo: 'my/path'
});
有没有办法这样做,使得otherwise重定向到不在应用程序中的页面?我尝试了。
$routeProvider
.when(...)
.otherwise({
    redirectTo: 'http://example.com'
});

但是这只是试图重定向到我的应用程序中不存在的路径。我知道的解决方案是在顶层控制器的$scope.$on('$routeChangeStart')中进行手动重定向,但这会导致大量代码重复(而且很丑陋)。是否有更好的方法?

4个回答

6
根据我的知识,这是不可能的,因为routeProvider仅处理内部路由。
不过你可以:
$routeProvider
.when(...)
.otherwise({
    controller: "404Controller",
    template: "<div></div>"
});

然后在控制器中只需使用window.location.href = 'http://yourExternalSite.com/404.html'即可。


5
在我的情况下,这对我起作用:
$routeProvider
.when('/my-path', {
    ...typical settings...
}).
.otherwise({
        redirectTo: function(obj, requestedPath) {
            window.location.href = appConfig.url404;
        }
});

这个修复方法对我有效(将重定向到同一主机上的非Angular资源)。 - Freek Wiekmeijer

5

正是我所需要的。谢谢。适用于Angular 1.5。 - Danielo515

2
我不建议在新控制器中只使用window.location.href,因为ngRoute会将历史记录设置为指向不存在的页面(因此当用户单击返回时,它将继续重定向到404页面)。我尝试过了,但失败了。
我想把你指向我的相关解决方案,这是针对另一个SO问题的: https://dev59.com/1mIk5IYBdhLWcg3wYtT7#27938693 我采用了那个方案并应用到了你的情况。我认为在ng-view之外使用MainCtrl并不是一个坏主意,除非你有嵌套的ng-view层次...我也没有看到任何代码重复,如果你很在意,可以将MainCtrl放在一个单独的模块中:
.config(['$routeProvider', function($routeProvider) {
  $routeProvider
  .when(..) 
  .otherwise({redirectTo: 'http://yourExternalSite.com/404.html'}); 
}])
.controller('MainCtrl',[ // <- Use this controller outside of the ng-view!
  '$rootScope','$window',
  function($rootScope,$window){
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
      // next.$$route <-not set when routed through 'otherwise' since none $route were matched
      if (next && !next.$$route) {
        event.preventDefault(); // Stops the ngRoute to proceed with all the history state logic
        // We have to do it async so that the route callback 
        // can be cleanly completed first, so $timeout works too
        $rootScope.$evalAsync(function() {
          // next.redirectTo would equal be 'http://yourExternalSite.com/404.html'
          $window.location.href = next.redirectTo;
        });
      }
    });
  }
]);

干杯


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接