在Angular中路由到非Angular页面

Routing to non-Angular pages within Angular

本文关键字:Angular 页面 路由      更新时间:2023-09-26

我正在将一个大型服务器渲染应用程序转换为使用Angular。由于尺寸的原因,我们一次做一点。在此转换期间,应用程序的一部分将使用Angular,另一部分将不使用。这意味着路由有时会在Angular应用程序中进行路由,有时需要从旧世界过渡到新世界(简单)或从新世界过渡到旧世界(困难)。

理想情况下,我想专门将Angular应用程序(新世界)中的一些页面转换路由到适当的控制器,但任何其他页面转换都应该只获取新的HTML页面(旧世界)。

我似乎不知道该怎么做。我想我需要使用routeProvider和when/otherwise,但我没有发现很多有用的文档。

您不能在旧世界中使用routeProvider,因为角度路由只能在实际的同一页面中引导您。

您可以为每个遗留路由制作一个占位符角度路由,然后在控制器中注入$window并执行以下操作:

$window.location.href = destinationUrl;

类似于:(注销时转到旧世界)

app.controller('LogoutCtrl', function ($scope, $window) {
    var destinationUrl = 'https://mywebsite.com/';
    $window.location.href = destinationUrl;
});

反之亦然,要回到有角度的世界,只需使用到有角度路线的正常链接:

<a href="angular-app/#/my/route">Link</a>

如果你想让一条包罗万象的路线重定向到外面,你可以做以下事情:

otherwise({
   controller: 'NotFoundCtrl'
  });
...
app.controller('NotFoundCtrl', function($scope, $location, $window) {
   var path = $location.path();
   $window.location.href="http://test.com" + path;
 })

正如triggerNZ所说,您总是可以让控制器将未处理的路由重定向到外部。这是HTML和Javascript展示了如何做到这一点

HTML

<div ng-app="myApp">
    <script type="text/ng-template" id="this.html">
        This Page.
    </script>
    <script type="text/ng-template" id="that.html">
        That Page.
    </script>
    <div>
        <ul>
            <li><a href="/this">This</a></li>
            <li><a href="/that">That</a></li>
            <li><a href="/other">Other</a></li>
        </ul>
        <ng-view></ng-view>
    </div>
</div>

Javascript

var app = angular.module("myApp", ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.when('/this', {
        templateUrl: 'this.html'
    }).when('/that', {
        templateUrl: 'that.html'
    }).otherwise({
        template: "<div></div>",
        controller: function ($window, $location, $rootScope) {
            if (!$rootScope.isInitialLoad) {
                $window.location.href = $location.absUrl();
            }
        }
    });
    $locationProvider.html5Mode(true);
});
app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function() {
        $rootScope.isInitialLoad = (typeof $rootScope.isInitialLoad === "undefined");
    });
});