简体   繁体   English

使用$ routeProvider重定向到Angular之外的路由

[英]Using $routeProvider to redirect to routes outside of Angular

I've written part of a web application in Angular. 我在Angular中编写了一个Web应用程序的一部分。 To ensure that all routes are covered, I wanted to add a redirectTo property to the $routeProvider , so that invalid routes are returned to the root of the web application, which doesn't use Angular. 为了确保覆盖所有路由,我想将redirectTo属性添加到$routeProvider ,以便将无效路由返回到Web应用程序的根目录,而不使用Angular。

I tried: 我试过了:

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

but obviously this only routes in the Angular controlled portion of the URL, so users would be redirected to a URL like http://app.com/angular-part-of-web-app# , instead of http://app.com , where I'd like them to go. 但显然这只是在URL的Angular控制部分中的路由,因此用户将被重定向到http://app.com/angular-part-of-web-app#类的URL,而不是http://app.com ,我希望他们去哪里。

I've worked around this by having a blank partial to act as a '404' page, and then a controller which just uses the $window object to redirect to the desired page: 我通过将一个空白部分用作'404'页面,然后使用$window对象重定向到所需页面的控制器来解决这个问题:

routes.js routes.js

// Redirect to site list.
$routeProvider.when('/404', {
    templateUrl: '/partials/404.html',
    controller: 'RedirectCtrl'
});

// Redirect to the 404 page.
$routeProvider.otherwise({
    redirectTo: '/404'
});

controllers.js controllers.js

// Controller to redirect users to root page of site.
.controller('RedirectCtrl', ['$scope', '$window', function ($scope, $window) {

    $window.location.href = '/';
}]);

However, this is setting off the 'too hacky, must be a better way' alarm bells. 然而,这是掀起'太hacky,必须是更好的方式'的警钟。 Is there a better way to do this in Angular? 在Angular有更好的方法吗?

EDIT: Angular routes - redirecting to an external site? 编辑: Angular路线 - 重定向到外部网站? didn't yield an answer to the same question. 没有回答同一个问题。 I'm going to leave my question open instead of marking it as a duplicate (for now), as with the Angular world moving so fast, the previous answer may no longer be the case. 我将打开我的问题,而不是将其标记为重复(现在),因为Angular世界移动如此之快,之前的答案可能不再是这样。

The above solution with /404 does not work for me. 使用/ 404的上述解决方案对我不起作用。 This however seems to work 然而,这似乎有效

.otherwise({
    controller : function(){
        window.location.replace('/');
    }, 
    template : "<div></div>"
});

PS. PS。 I am using Angular 1.2.10 我正在使用Angular 1.2.10

You could do something like this: 你可以这样做:

$routeProvider.when('/404', {
    controller: ['$location', function($location){
        $location.replace('/');
    }]
}).otherwise({
    redirectTo: '/404'
});

It is essentially the same thing, only it uses less code. 它基本上是相同的,只是它使用更少的代码。

Not sure what version of Angular JS the accepted answer was written on, but 'redirectTo' property takes in a function. 不确定是什么版本的Angular JS写了接受的答案,但'redirectTo'属性接受了一个函数。 So, why not do something simpler like this: 所以,为什么不做这样简单的事情:

$routeProvider.otherwise({
    redirectTo: function() {
        window.location = "/404.html";
    }
});

Obviously, you have to create your own 404.html. 显然,你必须创建自己的404.html。 Or wherever your 404 page is. 或者404页面的任何地方。

None of the answers including the marked answer worked for me. 包括明确答案在内的所有答案都不适合我。 I believe my solution solves your problem as well and I'd share my use-case as well for future readers' reference. 我相信我的解决方案也可以解决您的问题,我也会分享我的用例以供将来读者参考。

Issue with using the route controller method: When the controller is loaded the routing already have accessed the History API states for me (I use HTML5 mode, not sure whether this affects non-HTML5 mode). 使用路由控制器方法的问题:当加载控制器时,路由已经为我访问了历史API状态(我使用HTML5模式,不确定这是否会影响非HTML5模式)。

As a result, even though I can forward people to the correct page using window.location.replace('/');, if the user then clicks Back on their browser, it goes to invalid state. 因此,即使我可以使用window.location.replace('/');将人转发到正确的页面,如果用户然后在他们的浏览器上单击Back,它将进入无效状态。

Scenario: We implement multi-page model and I have my admin page module separate from my homepage (non-admin) modules. 场景:我们实现了多页模型,并且我的管理页面模块与我的主页(非管理员)模块分开。 I have a $location.path('/') somewhere in one of my admin controller, but since homepage isn't packaged into the admin page module, I want to force full page reload when I detect the '/' route. 我在我的一个管理员控制器中有一个$ location.path('/'),但由于主页没有打包到管理页面模块中,我想在检测到'/'路由时强制重页加载。

Solution: We have to intercept at the $routeChangeStart before ngRoute accesses any of the state info. 解决方案:我们必须在ngRoute访问任何状态信息之前拦截$ routeChangeStart。 This way we can even specify external href by passing url to redirectTo param in the $route 这样我们甚至可以通过将url传递给$ route中的redirectTo param来指定外部href

angular.module('app',['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider
  .when('/admin/default', {template: somePageTemplate})
  /*
   *  More admin-related routes here...
   */
  .when('/',{redirectTo:'/homepage'})  // <-- We want to intercept this
  .otherwise({redirectTo: '/admin/default'}); 
}])
.controller('MainCtrl',[ // <- Use this controller outside of the ng-view!
  '$rootScope','$window',
  function($rootScope,$window){
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
      // next <- might not be set when first load
      // next.$$route <- might not be set when routed through 'otherwise'
      // You can use regex to match if you have more complexed path...
      if (next && next.$$route && next.$$route.originalPath === '/') {
        // Stops the ngRoute to proceed
        event.preventDefault();
        // We have to do it async so that the route callback 
        // can be cleanly completed first, so $timeout works too
        $rootScope.$evalAsync(function() {
          // next.$$route.redirectTo would equal be '/homepage'
          $window.location.href = next.$$route.redirectTo;
        });
      }
    });
  }
]);

Please provide any feedback as I will be using this code myself. 请提供任何反馈,因为我将自己使用此代码。 Cheers 干杯

Reference: https://github.com/angular/angular.js/issues/9607 参考: https //github.com/angular/angular.js/issues/9607

Hi even though it's been two years, just for some one who search for this answer, simply use window.location.assign('/login'). 嗨即使已经两年了,只是为了寻找这个答案的人,只需使用window.location.assign('/ login')。 It's work for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM