角度路由-重定向到外部站点

Angular routes - redirecting to an external site?

本文关键字:外部 站点 重定向 路由      更新时间:2023-09-26

在AngularJS路由文件中,有一个otherwise路由选项,取代404:

$routeProvider
.when(...)
.otherwise({
    redirectTo: 'my/path'
});

有没有一种方法可以做到这一点,从而将重定向到不在应用程序中的页面?我试过

$routeProvider
.when(...)
.otherwise({
    redirectTo: 'http://example.com'
});

但这个jsut试图重定向到我的应用程序中的那个路径,但这个路径并不存在。我知道的解决方案是在顶级控制器中的$scope.$on('$routeChangeStart')中进行手动重定向,但这是大量的代码重复(而且很难看)。有更好的方法吗?

据我所知,这是不可能的,因为routeProvider只处理内部路由。

不过你能做的是

$routeProvider
.when(...)
.otherwise({
    controller: "404Controller",
    template: "<div></div>"
});

然后在控制器中仅使用CCD_ 4。

在我的案例中,这对我很有效:

$routeProvider
.when('/my-path', {
    ...typical settings...
}).
.otherwise({
        redirectTo: function(obj, requestedPath) {
            window.location.href = appConfig.url404;
        }
});

只需看看angular.js链接行为-禁用特定URL的深度链接

并使用这个

target="_self"

<a href="link" target="_self" >link</a>

我不建议像其他答案中指出的那样在新控制器中使用window.location.href,因为ngRoute会将历史记录设置为指向不存在的页面(因此当用户单击返回时,它将继续重定向到404页面)。我试过了,但失败了。

我想在这里向您介绍我对另一个SO问题的相关解决方案:https://stackoverflow.com/a/27938693/1863794

我采用了这一点,并将其应用于你的场景。我认为在ng视图之外使用MainCtrl并不是一个坏主意,因为除非你嵌套了ng视图的层,否则它只会声明一次。。。我也没有看到任何代码重复,如果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;
        });
      }
    });
  }
]);

干杯