Angular2 @ angular/router 3.0.0-alpha.3-更改路线时如何获取路线名称或路径 [英] Angular2 @angular/router 3.0.0-alpha.3 - How to get route name or path when route changes

查看:83
本文介绍了Angular2 @ angular/router 3.0.0-alpha.3-更改路线时如何获取路线名称或路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当路由更改时,我试图在我的app.component中获取当前路由名称或路由路径,以便可以将路由名称用作包装div周围的页面类.我正在尝试找出解决此问题的最佳方法.以前,我订阅了router更改属性,如下所示,但是@ angular/router 3.0.0-alpha.3似乎不再可用.如果有人有任何想法或建议,我将不胜感激.

I'm trying to get the current route name or route path in my app.component when the route changes so that I can use the route name as a page class around a wrapper div. I'm trying to figure out the best way to handle this. Previously I was subscribing to the router changes property like I have listed below, but it seems like this is no longer available with @angular/router 3.0.0-alpha.3. If anyone has any thoughts or suggestions I would be most grateful.

this.router.changes.subscribe((val) => {
  var path = this._location.path();
  if (path.indexOf('page-name') !== -1) {
    this.pageClass = 'page-name';
  }
})

推荐答案

史蒂夫(Steve)的答案是当前记录的答案,但是ActivatedRoute上可观察到的URL不会为我触发,除非我第一次点击基本URL时(例如:从/index到/index/item可以,但是从/index/item到index/item/2,index/dashboard甚至是/index都不行).

Steve's answer is the one documented currently, but the url observable on ActivatedRoute is not firing for me except when I first hit the base url (ex: going from /index to /index/item works, but going from /index/item to index/item/2, index/dashboard, or even /index does not).

我不确定以下解决方案是否是最佳实践,也不知道对性能有何影响,但是我能够通过以下方法在路由器的NavigationEnd事件上获取活动路由:

I'm not sure if the following solution is a best practice nor what the performance implications are, but I was able to get the active route on the NavigationEnd event of the router with the following:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ROUTER_DIRECTIVES, Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'navbar',
    directives: [ROUTER_DIRECTIVES], 
    template: `
                ...
              `    
})

export class NavBarComponent implements OnInit, OnDestroy {
    private sub: any;

    constructor(private router: Router) {
    }

    ngOnInit() {
        this.sub = this.router.events.subscribe(e => {
            if (e instanceof NavigationEnd) {
                console.log(e.url);
            } 
        });
    }


    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

每次更改路线时都会触发,无论您在url树中的位置有多深,或从哪里导航到/从哪里导航.

This fires every time you change the route, regardless of how deep you are in the url tree or where you navigate to/from.

这篇关于Angular2 @ angular/router 3.0.0-alpha.3-更改路线时如何获取路线名称或路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆