目前的文档只讨论了获取路由参数,而不是实际的路由段。

例如,如果我想找到当前路由的父,这是怎么可能的?


当前回答

这适用于与authguard一起使用的情况

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );

其他回答

给那些还在寻找这个的人。在Angular 2上。有几种方法。

constructor(private router: Router, private activatedRoute: ActivatedRoute){

   // string path from root to current route. i.e /Root/CurrentRoute
   router.url 

    // just the fragment of the current route. i.e. CurrentRoute
   activatedRoute.url.value[0].path

    // same as above with urlSegment[]
   activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))

   // same as above
   activatedRoute.snapshot.url[0].path

   // the url fragment from the parent route i.e. Root
   // since the parent is an ActivatedRoute object, you can get the same using 
   activatedRoute.parent.url.value[0].path
}

引用:

https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html https://angular.io/docs/ts/latest/api/router/index/Router-class.html https://angular.io/docs/ts/latest/guide/router.html

这个是在Angular 11上测试的

constructor(private router: Router) {
  this.router.events
   .pipe(filter((event: any) => event instanceof NavigationEnd))
   .subscribe((event: any) => {
     this.currentRoute = event.url;
     console.log(event);
   });
 }

Angular 2 rc2

router.urlTree.contains(router.createUrlTree(['/home']))

当我想要根据路线改变背景时,我面临着这个问题。但它只在我浏览网站时工作,而不是当我刷新页面时。

在router.events.subscribe()中,这是事件。导航时的Url,刷新时的this。router。Url。

现在它起作用了:

import { ActivatedRoute, Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

public ngOnInit() {
    this.router.events.subscribe((events:any) => {
        let theme = '';
        if (events instanceof NavigationStart) { theme = events.url; }
        else { theme = this.router.url; }
        
        if(theme === '/videos') { ... }
}

这很简单,在angular 2中,你只需要像这样导入Router库:

import { Router } from '@angular/router';

然后在组件或服务的构造函数中,你必须像这样实例化它:

constructor(private _router: Router) {}

然后在代码的任何部分,函数、方法、构造等等:

      this._router.events
        .subscribe(
            (url:any) => {
                let _ruta = "";
                url.url.split("/").forEach(element => {
                    if(element!=="" && _ruta==="")
                        _ruta="/"+element;  
                });
                console.log("route: "+_ruta); //<<<---- Root path
                console.log("to URL:"+url.url); //<<<---- Destination URL                    
                console.log("from URL:"+this._router.url);//<<<---- Current URL
            });