2017-01-03 4 views
1

나는 ngUpgrade를 사용하고 있으며 ng2와 ng1 사이의 라우팅을 처리하는 방법을 모른다. 내가 ng2 구성 요소에 있다면 ng1 컨트롤러로 어떻게 라우팅합니까? 그 반대.ngUpgrade - ng2에서 ng1로 라우팅 - 방법?

ng1에 ui-router를 사용하고 있습니다. ng2의 경우 각도 팀에서 라우터를 사용하고 있습니다.

감사합니다.

답변

4

먼저 Angular 1.x 및 2.x 앱에서 경로를 정상적으로 정의해야합니다.

app.config(function($routeProvider) { 
     $routeProvider 

      // route for the home page 
      .when('/', { 
       templateUrl : 'pages/home.html', 
       controller : 'mainController' 
      }) 

      // route for the about page 
      .when('/about', { 
       templateUrl : 'pages/about.html', 
       controller : 'aboutController' 
      }) 

      // route for the contact page 
      .when('/contact', { 
       templateUrl : 'pages/contact.html', 
       controller : 'contactController' 
      }); 
    }); 

와의

Module 2 각도 :

Module.config(($routeProvider) => { 
    $routeProvider 
    .when('/user/:id',  {template : '<user-details></userdetails>'}) 
    .when('/users', {template : '<user-list></userlist>'}); 
}); 
당신은 Ng1Ng2UrlHandlingStrategy라는 클래스를 생성하고 거기에 그들 사이에 경로를으로 나눔 수

:

class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy { 
    shouldProcessUrl(url) { return url.toString().startsWith("/home") || url.toString().startsWith("/aboute") || url.toString().startsWith("/contact"); } 
    extract(url) { return url; } 
    merge(url, whole) { return url; } 
} 

그리고 당신의 주요 구성 요소를 :

providers: [ 
    // Providing a custom url handling strategy to tell the Angular 2 router 
    // which routes it is responsible for. 
    { provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy } 
] 

마지막으로 root 구성 요소를 업데이트하여 각도 2 라우터 콘센트를 포함시킵니다.

@Component({ 
    selector: 'root-cmp', 
    template: ` 
    <router-outlet></router-outlet> 
    <div class="ng-view"></div> 
    `, 
}) 
export class RootCmp {} 
+0

유익한 답변 주셔서 감사합니다. 누락 된 부분이 있습니다. ng2에서 ng1로 상태를 어떻게 전송합니까? ng2 구성 요소에서 "$ state.go"표현식을 찾고 있습니다. – einav

+0

그 요점은 모든 경로가 ng2에 의해 처리되고 그 클래스가 처리 할 경로와하지 않을 경로를 결정하는 것입니다. shouldProcessUrl에서 논리를 살펴 봅니다. – Yaser

+2

내 shouldProcessUrl은 항상 '/'(실제 내가 넣은 URL) – Kesty