簡體   English   中英

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

[英]Angular routes - redirecting to an external site?

在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>"
});

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

就我而言,這對我有用:

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

只需看看angular.js鏈接行為 - 禁用特定URL的深層鏈接

並使用這個

TARGET = “_自我”

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

我不建議在新控制器中使用window.location.href,如其他答案中所指出的那樣,因為ngRoute會將歷史記錄設置為指向不存在的頁面(因此當用戶點擊它時,它將繼續重定向到404頁)。 我試過但失敗了。

我想在此向您指出另一個SO問題的相關解決方案: https//stackoverflow.com/a/27938693/1863794

我采用了它並應用於您的場景。 我不認為在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;
        });
      }
    });
  }
]);

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM