Angular 4获取儿童路线参数

问题描述 投票:0回答:2

在我的申请中,路线是这样的: -

{ 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不会触发错误,但会在激活路径时传递子参数。

angular angular-routing
2个回答
1
投票

你可以这样做:

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,
    };
}

0
投票

我最终实现了以下解决方案: -

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');

            }

        }

     });
© www.soinside.com 2019 - 2024. All rights reserved.