加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular2 @ angular / router 3.0.0-alpha.3 – 路

发布时间:2020-12-17 17:46:16 所属栏目:安全 来源:网络整理
导读:我正在尝试在路由更改时获取app.component中的当前路由名称或路由路径,以便我可以将路由名称用作包装器div周围的页面类.我正试图找出解决这个问题的最佳方法.以前我订阅了路由器更改属性,就像我在下面列出的那样,但似乎不再提供@ angular / router 3.0.0-alp
我正在尝试在路由更改时获取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';
  }
})

解决方法

史蒂夫的答案是目前记录的答案,但是ActivatedRoute上的url可观察对我来说并不是因为我第一次点击基本网址(例如:从/ 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();
    }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读