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

时间:2018-01-02 09:47:30

标签: angular angular2-routing

我想检查父组件中的活动子路由,但我不知道如何获取它。我正在尝试使用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'`
    
  3. 有什么想法吗?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

There's an overload to RxJS filter that makes it into a typeguard. The output then becomes an actual NavigationError object instead of just being a RouterEvent.

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

Anything after this in your pipe(...) will be of type NavigationEnd and will have url on it.

I recommend creating a helper service called something like RouterEventsService and creating common observables on it that you can use from anywhere.

Just a simple service like this:

@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));
}

答案 2 :(得分:-1)

别忘了导入rxjs

import 'rxjs/add/operator/filter';