Angular2 @angular/router 3.0.0-alpha.3 - How to get route name or path when route changes

前端 未结 2 2003
时光取名叫无心
时光取名叫无心 2021-02-10 07:15

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 t

2条回答
  •  春和景丽
    2021-02-10 08:01

    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).

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

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

提交回复
热议问题