如何获取当前路径

How to get current route

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

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

Location 注入您的组件并读取 location.path(); 您需要在某处添加 ROUTER_DIRECTIVES 以便 Angular 可以解析 Location 您需要将 import: [RouterModule] 添加到模块中。

更新

在 V3 (RC.3) 路由器中,您可以注入 ActivatedRoute 并使用其 snapshot 属性.

访问更多详细信息
constructor(private route:ActivatedRoute) {
  console.log(route);
}

constructor(private router:Router) {
  router.events.subscribe(...);
}

另见

在 Angular2 Rc1 中你可以注入一个 RouteSegment 然后将它传递给 .navigate() 方法:

constructor(private router:Router,private segment:RouteSegment) {}

ngOnInit() {
  this.router.navigate(["explore"],this.segment)
}

angular 2 rc2

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

新的 V3 路由器有 url 属性。

this.router.url === '/login'

您可以使用ActivatedRoute获取当前路由器

原答案(RC版)

我在 AngularJS Google Group 上找到了解决方案,而且非常简单!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

这是原答案

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

Angular RC4:

您可以从 @angular/router

导入 Router

然后注入:

constructor(private router: Router ) {

}

然后调用它的URL参数:

console.log(this.router.url); //  /routename

你可以试试

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

constructor(private router: Router, private activatedRoute:ActivatedRoute) {
console.log(activatedRoute.snapshot.url)  // array of states
console.log(activatedRoute.snapshot.url[0].path) }

其他方式

router.location.path();   this works only in browser console. 

window.location.pathname 给出路径名。

为了您的目的,您可以使用 this.activatedRoute.pathFromRoot

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){

}

在 pathFromRoot 的帮助下,您可以获得父 url 列表并检查 URL 的所需部分是否符合您的条件。

有关更多信息,请查看这篇文章 http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ 或者从 npm

安装 ng2-router-helper
npm install ng2-router-helper

对于新路由器 >= RC.3

最好和最简单的方法是!

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"
}

这可能是你的答案,使用激活路由的 params 方法从你想阅读的 URL/route 获取参数,下面是演示片段

import {ActivatedRoute} from '@angular/router'; 
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
             this.yourVariable = params['required_param_name'];
        });
    }
}

使用 angular 2.2.1(在基于 angular2-webpack-starter 的项目中)工作如下:

export class AppComponent {
  subscription: Subscription;
  activeUrl: string;

  constructor(public appState: AppState,
              private router: Router) {
    console.log('[app] constructor AppComponent');
  }

  ngOnInit() {
    console.log('[app] ngOnInit');
    let _this = this;
    this.subscription = this.router.events.subscribe(function (s) {
      if (s instanceof NavigationEnd) {
        _this.activeUrl = s.urlAfterRedirects;
      }
    });
  }

  ngOnDestroy() {
    console.log('[app] ngOnDestroy: ');
    this.subscription.unsubscribe();
  }
}

在 AppComponent 的模板中,您可以使用例如{{activeUrl}}.

此解决方案的灵感来自于 RouterLinkActive 的代码。

对于那些仍在寻找这个的人。在 Angular 2.x 上有几种方法。

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
}

参考文献:

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

以下是 Angular 2.3.1 中对我有用的内容。

location: any;

constructor(private _router: Router) { 

      _router.events.subscribe((data:any) => { this.location = data.url; });

      console.warn(this.location);  // This should print only path e.g. "/home"
}

data 是一个对象,我们需要包含在该对象中的 url 属性。所以我们在变量中捕获该值,我们也可以在 HTML 页面中使用该变量。例如,我只想在用户位于主页时显示 div。在这种情况下,我的路由器 url 值将是 /home。所以我可以用下面的方式写一个div:

<div *ngIf="location == '/home'">
This is content for the home page.
</div>

这个很简单,在angular2中你只需要像这样导入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
            }); 

我在使用

时遇到了同样的问题
this.router.url

我得到了带有查询参数的当前路线。我所做的解决方法是改用它:

this.router.url.split('?')[0]

不是一个很好的解决方案,但很有帮助。

获取路线段:

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

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }

要找到当前路由的父路由,可以从路由器获取UrlTree,使用相对路由:

var tree:UrlTree = router.createUrlTree(['../'], {relativeTo: route});

然后获取主出口的网段:

tree.root.children[PRIMARY_OUTLET].segments;

使用这个

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

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

并在 main.ts 中导入

import 'rxjs/add/operator/filter';

编辑

现代方式

import {filter} from 'rxjs/operators';

router.events.pipe(
    filter(event => event instanceof NavigationEnd)
)
    .subscribe(event => {
        console.log(event);
    });

原生 window 对象也可以正常工作

console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);

注意:请勿在服务器端渲染中使用它

this.router.events.subscribe((val) => {
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
});

要可靠地获取完整的当前路线,您可以使用此

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.url);
    }
  }
);

短版如果你导入了路由器那么你可以简单地使用像

这样的东西

this.router.url === "/search"

否则执行以下操作

1) 导入路由器

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

2) 在构造函数中声明其入口

constructor(private router: Router) { }

3) 在你的函数中使用它的值

yourFunction(){
    if(this.router.url === "/search"){
        //some logic
    }
}

@victor 的回答对我有帮助,这和他的回答一样,但有一点细节,因为它可能对某人有帮助

截至目前,我的路径如下 -

this.router.url.subscribe(value => {
    // you may print value to see the actual object
    // console.log(JSON.stringify(value));
    this.isPreview = value[0].path === 'preview';
})

其中,routerActivatedRoute

的实例

WAY 1: Using Angular: this.router.url

import { Component } from '@angular/core';

// Step 1: import the router 
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    //Step 2: Declare the same in the constructure.
    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        // Do comparision here.....
        ///////////////////////////
        console.log(this.router.url);
    }
}

WAY 2 Window.location as we do in the Javascript, If you don't want to use the router

this.href= window.location.href;

如果您需要访问当前url,通常您必须等待NavigationEnd 或NavigationStart 执行某些操作。如果您只是订阅路由事件,订阅将在路由生命周期中输出许多事件。相反,使用 RxJS 运算符仅过滤您需要的事件。这样做的好处是现在我们有了更严格的类型!

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

当用户浏览应用程序访问[=27=时,我遇到了需要URL路径的问题](或在特定 URL 上刷新)显示基于 URL 的子组件。

此外,我想要一个可以在模板中使用的 Observable,所以 router.url 不是一个选项。也没有 router.events 订阅,因为路由是在组件模板初始化之前触发的。

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => event.url)
);

希望对你有所帮助,祝你好运!

在组件文件中:

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

constructor(state: ActivatedRouteSnapshot) {
    console.log(state.path)
}

在路由文件中:

router.events.subscribe(e => {
      if (e instanceof NavigationEnd) {
        this.currentUrl = e.url;
      }
    });

可以在.ts文件中使用

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

constructor(private router: Router) {}

this.router.events.subscribe(value => {
      if (value instanceof NavigationStart) {
        console.log(value) // your current route
      }
    });
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}
import { Router, NavigationEnd } from "@angular/router";

constructor(private router: Router) {
  // Detect current route
  router.events.subscribe(val => {
    if (val instanceof NavigationEnd) {
      console.log(val.url);
    }
  });
}
import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}

要在 angular 8 中获取当前路由器,只需执行此操作

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

然后像

一样在构造函数中注入它
constructor(private route: ActivatedRoute){}

如果你想获取当前路线然后使用这个route.url

如果你有像 /home/pages/list 这样的多名称路由并且你想访问个人那么你可以像这样访问每个 route.url.value[0].path

value[0] 会给主页,value[1] 会给你页面,value[2] 会给你列表

如果您无法访问 router.url(例如,如果您使用了 skipLocationChange),您可以使用以下更简单的方法:

import { Location } from '@angular/common';    
constructor(private readonly location: Location) {}
    
ngOnInit(): void {
  console.log(this.location.path());
}

如果您将它与 authguard 一起使用,这适用

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

最简单的方法

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  <---------- to get only path eg:"/signUp"
}

这个是在 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);
   });
 }

对我来说,在 AuthGuardService implements CanActivate 中访问当前路线时,接受的答案不起作用,因为路线尚未完全处理。我在这里回答了同样的问题 () 但如果你只是想从这里复制粘贴,这是我的解决方案:

const finalUrl = this.router.getCurrentNavigation()?.finalUrl;   
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login';