在我的申请中,路线是这样的: -
{ path: 'route-a', component: ComponentA, children : [
{ path: ':param-b', component: ChildComponentB, children : [
{ path: ':param-c', component: ChildComponentC }
]}
]},
现在在我的ComponentA
我试图订阅儿童param得到param-b
this.routefirstChild$ = this.route.firstChild.params.subscribe($routefirstChild => {
console.log($routefirstChild, '$routefirstChild');
});
现在,当我导航到example.com/route-a
时,我得到this.route.firstChild is null
错误。
但是,如果我导航到example.com/route-a/1234
,那么param就会通过。必须订阅的哪个observable不会触发错误,但会在激活路径时传递子参数。
你可以这样做:
function getChildMostRoute(route: ActivatedRoute) {
let route = route.snapshot;
// Get the current active descendent
while (route.firstChild) {
route = route.firstChild;
}
const allPathsJoined = route.pathFromRoot
.map(s => s.url.map(u => u.path).join('/'))
.join('/')
return {
path: allPathsJoined,
params: route.queryParams,
};
}
我最终实现了以下解决方案: -
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
this.routeEvents$ = this.router.events.subscribe(
( $routeEvents ) : void => {
if ( $routeEvents instanceof NavigationEnd ) {
if(typeof this.route.firstChild != "undefined" && this.route.firstChild){
console.log(this.route.firstChild.snapshot.params, 'this.route.firstChild.snapshot.params');
}
}
});