programing

$routeProvider를 사용한 Angular 외부 경로 리다이렉트

newnotes 2023. 4. 5. 22:12
반응형

$routeProvider를 사용한 Angular 외부 경로 리다이렉트

앵귤러수 위해서, 「」를 하고 싶다고 .redirectTo의 property에 $routeProvider그러면 비활성 루트가 Angular를 사용하지 않는 웹 응용 프로그램의 루트로 반환됩니다.

나는 시도했다.

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

의 Angular 는 "URL" "Angular controlled" 등의 .http://app.com/angular-part-of-web-app# 「」가 아닌 「」http://app.com어디로 갔으면 좋겠는데

'과 '404' 페이지 을 하는 $window원하는 페이지로 리다이렉트할 수 있습니다.

routes.displaces

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

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

controllers.controllers.displaces

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

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

하지만, 이것은 '너무 진부한, 더 나은 방법임에 틀림없다'라는 경종을 울리고 있다.Angular에서 더 좋은 방법이 있을까요?

편집: 각도 경로 - 외부 사이트로 리디렉션? 같은 질문에 대한 답변이 없습니다.Angular의 세계가 매우 빠르게 움직이고 있기 때문에 이전 답변은 더 이상 해당되지 않을 수 있으므로 질문을 복제로 표시하지 않고 열어 둡니다.

위의 /404 솔루션으로는 문제 없습니다.하지만 이것은 효과가 있는 것 같다.

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

PS. Angular 1.2.10을 사용하고 있습니다.

승인된 답변이 작성된 Angular JS의 버전을 알 수 없지만 'redirectTo' 속성은 함수를 사용합니다.그렇다면 다음과 같이 간단한 작업을 수행하는 것이 어떨까요?

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

물론 404.html을 직접 작성해야 합니다.404 페이지가 어디에 있든 상관없습니다.

다음과 같은 작업을 수행할 수 있습니다.

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

이것은 본질적으로 같은 것입니다만, 코드를 적게 사용합니다.

표기된 답안까지 하나도 안 통했어요.제 솔루션도 당신의 문제를 해결해 줄 것이라고 생각합니다.또, 장래의 독자가 참조할 수 있도록, 사용 사례를 공유하겠습니다.

루트 컨트롤러 방식 사용에 관한 문제:컨트롤러가 로드되었을 때 라우팅은 이미 History API 상태에 접속되어 있습니다(HTML5 모드를 사용하고 있습니다만, 이것이 비HTML5 모드에 영향을 줄지는 잘 모르겠습니다).

그 결과 window.location.replace('/')를 사용하여 사용자를 올바른 페이지로 전송할 수 있는데 사용자가 브라우저에서 Back을 클릭하면 비활성화 상태가 됩니다.

시나리오:여러 페이지 모델을 구현하고 있으며, 홈페이지(비관리) 모듈과는 별도로 관리 페이지 모듈을 사용하고 있습니다.관리자 컨트롤러 중 하나에 $location.path('/')가 있지만 홈페이지는 관리 페이지 모듈에 패키지되어 있지 않기 때문에 '/' 경로를 감지하면 페이지 전체를 새로고침해야 합니다.

솔루션:ngRoute가 상태 정보에 액세스하기 전에 $routeChangeStart에서 대행 수신해야 합니다.이렇게 하면 $route의 redirectTo param에 URL을 전달함으로써 외부 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;
        });
      }
    });
  }
]);

제가 직접 이 코드를 사용할 테니 피드백 부탁드립니다.건배.

레퍼런스: https://github.com/angular/angular.js/issues/9607

안녕하세요. 2년이 지났지만 이 답변을 검색하는 사람은 window.location.assign('/login')을 사용하십시오.나한텐 일인데.

언급URL : https://stackoverflow.com/questions/19321765/using-routeprovider-to-redirect-to-routes-outside-of-angular

반응형