如何在父组件Angular 2中获取活动子路由

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

我想检查父组件中的活动子路由,但我不知道如何获取它。我试图使用ActivatedRoute但无法得到它。

我尝试过Angular2 (rc4) - Check active child route in parent component的两个答案:

  1. 我尝试过接受的答案: constructor( private router:Router, private route: ActivatedRoute ) { var state = this.router.routerState var children = state.children(this.route) } 有了这个,我收到这个错误: Property 'children' does not exist on type 'RouterState'
  2. 我也尝试过这个: this.router.events.filter(evt => evt instanceof NavigationEnd) .map(evt => evt.url) .subscribe(url => console.log(url)); 但是用这个得到这些错误: property 'url' does not exist on type 'Event' property 'url' does not exist on type 'RouteConfigLoadStart'`

任何的想法?

angular angular2-routing
3个回答
3
投票

我会说Angular(通过TypeScript)只是非常严格的类型。你可以解决它...这是一个简单的例子,只是获取直接子路径的名称/路径。

this.router.events.filter(evt => evt instanceof NavigationEnd)
        .subscribe((event) => {
            console.log(event['url']);
            console.log(this.route.firstChild.routeConfig.path);
        });

1
投票

RxJS filter过载导致它成为一名打字机。然后输出成为一个真正的NavigationError对象,而不仅仅是一个RouterEvent

   this.router.events.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd));

在你的pipe(...)之后的任何东西将是NavigationEnd类型,并将有url

我建议创建一个名为RouterEventsService的辅助服务,并在其上创建可以在任何地方使用的常见observable。

这是一个简单的服务:

@Injectable({ providedIn: 'root' })
export class RouterEventsService
{
    constructor(private router: Router) {}

    // navigation lifetime
    navigationStart$ = this.router.events.pipe(filter((e): e is NavigationStart => e instanceof NavigationStart));
    navigationEnd$ = this.router.events.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd));

    // you can add clever things to it as needed
    navigationDurationMs$ = this.navigationStart$.pipe(switchMap(() => 
    {
        const startTime = new Date().getTime();
        return this.navigationEnd$.pipe(take(1), map(() => new Date().getTime() - startTime));
    }), 
    shareReplay(1));
}

-1
投票

别忘了导入rxjs

import 'rxjs/add/operator/filter';
© www.soinside.com 2019 - 2024. All rights reserved.