【问题标题】:Angular2 (rc4) - Check active child route in parent componentAngular2 (rc4) - 检查父组件中的活动子路由
【发布时间】:2016-07-30 09:31:51
【问题描述】:

我正在尝试检查父组件中的活动子路由,但我遇到了困难。

我尝试通过执行以下操作来订阅 ActivatedRoute:

class ParentComponent {
    constructor(private _route:ActivatedRoute) {}

    ngOnInit() {
        this._route.data.subscribe(value => console.log(value)});
    }
}

我在 Stack Overflow 上阅读了很多帖子,但找不到检查和更新有关父组件的子路由的解决方案。

有什么想法吗?

【问题讨论】:

    标签: typescript angular router


    【解决方案1】:

    在编写这些行时,所选答案似乎不再起作用。

    如果你想在路由改变时得到通知,你可以订阅Router.events observable。例如,NavigationEnd 事件将 url 存储为属性:

     this.router.events.filter(evt => evt instanceof NavigationEnd)
                       .map(evt =>evt.url)
                       .subscribe(url=>console.log(url));
    

    如果您想将当前路由与子路径进行比较 - 假设为 "child"-。您可以使用Router.isActive() 方法:

    let events = this.router.events;
    events.filter(evt => evt instanceof NavigationEnd)
           .map(() =>{
                let exact=true;
                let childRoute=this.router.createUrlTree(["child"], {relativeTo: this.route}
                return this.router.isActive(childRoute,exact);
            })
            .subscribe(active=>console.log(`child route is active :${active`));
    

    注意事项:

    • this.routerRouter 实例
    • this.routeActivatedRoute 的一个实例
    • exact 用于精确匹配:如果路由是 "child/grand-child" this.router.isActive(route,true) 将返回 false

    【讨论】:

    • 收到此错误.. property 'url' does not exist on type 'Event' property 'url' does not exist on type 'RouteConfigLoadStart'
    • @Aakriti 您需要过滤路由器事件并且只接受NavigationEnd 事件。 this.router.events.filter(evt => evt instanceof NavigationEnd)(可能您需要将类型断言为Observable<NavigationEnd>,如下所示:this.router.events.filter(evt => evt instanceof NavigationEnd) as Observable<NavigationEnd>
    • 我们将如何使用 map 与这个 .. 它在说 cannot find name map
    【解决方案2】:

    您可以使用以下代码 sn-p 访问活动子路由

    constructor(private router:Router, private currentActivatedRoute:ActivatedRoute)
    // this should be called in ngOnInit
        var state = this.router.routerState
        var children = state.children(this.currentActivatedRoute)
    

    RouterState, Tree

    【讨论】:

    • Property 'children' does not exist on type 'RouterState' ... :/
    • 不确定自发布此答案后是否发生了变化,但 children 是 ActivatedRoute 的属性,而不是 Router
    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 2016-07-24
    • 1970-01-01
    • 2016-05-20
    • 2016-08-28
    • 2018-01-07
    • 2018-06-12
    • 2016-10-28
    相关资源
    最近更新 更多