2016-10-03 2 views
6

비슷한 질문은 Angular2 Get router params outside of router-outlet이지만 출시 버전 인 각도 2 (라우터 버전 3.0.0)를 대상으로합니다. 연락처 목록과 라우터 콘센트가있는 앱을 사용하여 선택한 연락처를 표시하거나 편집 할 수 있습니다. 나는 적절한 접촉이 어떤 시점 (페이지로드를 포함하여)에서 선택되었는지 확인하고 싶기 때문에 경로가 바뀔 때마다 "id"매개 변수를 읽을 수 있기를 바란다.각도 2 : 라우터 출구 밖에서 경로 매개 변수를 가져 오려면

라우터의 이벤트 속성을 구독하여 라우팅 이벤트를 처리 할 수는 있지만 이벤트 개체를 사용하면 구문 분석되지 않은 원시 URL에 액세스 할 수 있습니다. 라우터의 parseUrl 메서드를 사용하여 구문 분석 할 수 있지만이 형식은 특히 유용하지 않으며 다소 취약하기 때문에 차라리 사용하지 않을 것입니다. 라우팅 이벤트에서 라우터의 routerState 속성을 모두 보았지만 params는 항상 스냅 샷의 빈 개체입니다.

방금 ​​전에 내가 놓친 실제 방법이 있습니까? 이 작업 목록을 변경하지 않는 라우터 콘센트에 연락처 목록을 포함시켜야합니까?

답변

0

나는 하루 종일이 문제에 어려움을 겪어 왔지만, 나는 특히 라우터 이벤트 중 하나를 듣는 방법으로 마침내이 방법을 알아 냈다고 생각합니다. 준비가되어있는 것, 조금 까다 롭다 (못 생겼습니까?)하지만 오늘은 Angular (4.x)와 Angular Router (4.x)의 최신 버전에서 작동합니다. 이 코드 조각은 나중에 무언가를 변경하면 작동하지 않을 수도 있습니다.

기본적으로 경로 경로를 얻은 다음 나 혼자 맞춤 매개 변수지도를 다시 작성하는 방법을 찾았습니다.

그래서 여기있다 :

import { Component, OnInit } from '@angular/core'; 
import { Router, RoutesRecognized } from '@angular/router'; 

@Component({ 
    selector: 'outside-router-outlet', 
    templateUrl: './outside-router-outlet.component.html', 
    styleUrls: ['./outside-router-outlet.component.css'] 
}) 

export class OutSideRouterOutletComponent implements OnInit { 
    path: string; 
    routeParams: any = {}; 

    constructor(private router: Router) { } 

    ngOnInit() { 
    this.router.events.subscribe(routerEvent => { 
     if (routerEvent instanceof RoutesRecognized) { 
      this.path = routerEvent.state.root['_routerState']['_root'].children[0].value['_routeConfig'].path; 
      this.buildRouteParams(routerEvent); 
     } 
    }); 
    } 

    buildRouteParams(routesRecognized: RoutesRecognized) { 
    let paramsKey = {}; 
    let splittedPath = this.path.split('/'); 
    splittedPath.forEach((value: string, idx: number, arr: Array<string>) => { 
     // Checking if the chunk is starting with ':', if yes, we suppose it's a parameter 
     if (value.indexOf(':') === 0) { 
     // Attributing each parameters at the index where they were found in the path 
     paramsKey[idx] = value; 
     } 
    }); 
    this.routeParams = {}; 
    let splittedUrl = routesRecognized.url.split('/'); 
    /** 
    * Removing empty chunks from the url, 
    * because we're splitting the string with '/', and the url starts with a '/') 
    */ 
    splittedUrl = splittedUrl.filter(n => n !== ""); 
    for (let idx in paramsKey) { 
     this.routeParams[paramsKey[idx]] = splittedUrl[idx]; 
    } 
    // So here you now have an object with your parameters and their values 
    console.log(this.routeParams); 
    } 
} 
관련 문제