나는 하루 종일이 문제에 어려움을 겪어 왔지만, 나는 특히 라우터 이벤트 중 하나를 듣는 방법으로 마침내이 방법을 알아 냈다고 생각합니다. 준비가되어있는 것, 조금 까다 롭다 (못 생겼습니까?)하지만 오늘은 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);
}
}