2016-07-11 3 views
22

angular2 router을 사용 중입니다.Angular2 라우터, 경로 정보를 URL에서 가져와 빵 부스러기 표시

  1. site.com/a/b/c/15의 경로를 확인하고 경로에 관련된 꽤 이름을 가져올 수 :

    는, URL의 이동 경로를 그리려면 다음 작업을 수행 할 site.com/a/b/c/15을 말할 수
  2. site.com/a/b/c의 경로를 확인하고 경로
  3. 에 관련된 꽤 이름을 얻을 site.com/a/b의 경로를 확인하고 경로
  4. 에 관련된 꽤 이름을 얻을 site.com/a의 경로를 가져옵니다과 관련된 예쁜 이름을 얻을 패주 전자

그래서 나는 다음과 같은 경로가 어떻게 말할 수 :

{ path: 'a', component: A, data:{prettyName: 'I am A'}} 
{ path: 'b', component: B, data:{prettyName: 'I am B'}}, 
{ path: 'c', component: C, data:{prettyName: 'I am C'}}, 

내 프로세스의 결과가 내가 현재를 설명하는 좋은 이동 경로 "I am A > I am B > I am C"를 표시 할 수에 {"I am C", "I am B", "I am C"} 및 감사를 포함한 배열 것을 노선.

지금 그러나 라우터되지 않는 일을

this.router.recognize(url).then((instruction) => { 
    instruction.component.routeData.get('prettyName') // Would return 'I am ..' 

와 함께 작동하는이 사용; 마지막 라우터와 나는 더 이상 인식 논리를 처리 할 수 ​​없습니다.

URL과 연결된 경로 데이터를 얻는 방법은 무엇입니까?

답변

2
는 지금까지 가장 feasable 솔루션 (완료)되어

:

  • 수출/수입 할
  • router.events은 URL 변경에
  • 가입에서 현재의 URL 업데이트를 가져 오기, 루프 경로를 확인 경로의 경로에서 패턴이 URL과 일치하는지 확인하십시오.
  • 패턴이 URL과 일치하면 일치하는 경로에서 데이터를 가져옵니다.

장점 :

단점을 작동 : 다시 실행, URL 경로를 인식 manuall을 하나

22

현재 URL에서 시작에서 경로를 얻으려고 노력의

대신 RC5에 대한 업데이트 날짜 NG2 라우터를 사용하지 않고 각 성공적인 탐색 lifecycl의 종료 후

: URL이, 당신은 RouterState에서 (주 출구와 관련된) 활성화 된 경로를 모두 얻을 수 있습니다 e에서 라우터는 라우터의 현재 상태를 구성하는 ActivatedRoute의 트리를 만듭니다. Router 서비스와 routerState 속성을 사용하여 애플리케이션의 어느 곳에서나 현재 RouterState에 액세스 할 수 있습니다.

라우터 상태는 부모, 자녀 및 형제 경로에서 필요할 수있는 정보를 얻기 위해 활성화 된 모든 경로에서 경로 트리를 위아래로 탐색하는 방법을 제공합니다.

import { Component } from '@angular/core'; 
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router'; 
import 'rxjs/add/operator/filter'; 

@Component({ 
    selector: 'breadcrumbs', 
    template: ` 
    <div> 
    breadcrumbs: 
    <span *ngFor="let breadcrumb of breadcrumbs; let last = last"> 
     <a [routerLink]="breadcrumb.url">{{breadcrumb.label}}</a> 
     <span *ngIf="!last">></span> 
    </span> 
    </div>` 
}) 
export class BreadcrumbsComponent { 
    breadcrumbs: Array<Object>; 
    constructor(private router:Router, private route:ActivatedRoute) {} 
    ngOnInit() { 
    this.router.events 
     .filter(event => event instanceof NavigationEnd) 
     .subscribe(event => { // note, we don't use event 
     this.breadcrumbs = []; 
     let currentRoute = this.route.root, 
      url = ''; 
     do { 
      let childrenRoutes = currentRoute.children; 
      currentRoute = null; 
      childrenRoutes.forEach(route => { 
      if(route.outlet === 'primary') { 
       let routeSnapshot = route.snapshot; 
       console.log('snapshot:', routeSnapshot) 
       url += '/' + routeSnapshot.url.map(segment => segment.path).join('/'); 
       this.breadcrumbs.push({ 
       label: route.snapshot.data.breadcrumb, 
       url: url }); 
       currentRoute = route; 
      } 
      }) 
     } while(currentRoute); 
     }) 
    } 
} 

경로는 다음과 같이 :

{ path: '', component: HomeComponent, data: {breadcrumb: 'home'}} 
- reference

root에서 ActivatedRoute의의 트리를 걸어, 각 NavigationEnd 이벤트 후, 다음, 라우터 이벤트에 가입

Plunker - RC.5, 라우터 3.0.0-rc.1


비슷한 솔루션도 https://stackoverflow.com/a/38310404/215945 참조하십시오.

+5

나는 더 세련된 버전을 만들었습니다. https://github.com/alalonde/ng2-breadcrumbs – alalonde

+0

이것이 빵 부스러기와 같은 간단한 것에 대한보기 흉한 해결책이라고 생각합니다. – hendrix

+1

@hendrix, alalonde가 github repo에서 언급 한 것처럼 "네비게이션 계층 구조가 URL의 슬래시와 직접적으로 일치하지 않을 수 있기 때문에 복잡하거나 추한 것입니다." –