首页 文章

Angular2 @ angular / router 3.0.0-alpha.3 - 如何在路由更改时获取路由名称或路径

提问于
浏览
5

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

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

2 回答

  • 0

    Steve的答案是目前记录的答案,但是 ActivatedRoute 上的url observable并没有为我开火,除非我第一次点击基本网址(例如:从/ index到/ index / item工作,但从/ index / item转到index / item / 2,索引/仪表板,甚至/索引都没有) .

    我不确定以下解决方案是否是最佳实践,性能影响是什么,但我能够在路由器的 NavigationEnd 事件中获得活动路由,具有以下内容:

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

    无论您在网址树中的深度或导航到/从的位置,每次更改路径时都会触发此操作 .

  • 7

    这可能会有所帮助,

    import { CanActivate, Router, RouterStateSnapshot } from '@angular/router';
    
    @Component({
      selector: 'my-component',
      templateUrl: 'my-component.html'
    })
    export class MyComponent implements CanActivate {
      constructor(private router: Router) {}
    
      canActivate(state: RouterStateSnapshot) {
       // this is the future route you are intended to visit
       console.log(state.url);
      }
    }
    

    更多详情,请致电https://angular.io/docs/ts/latest/guide/router.html

相关问题