如何获取当前路线

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

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

958596 次浏览

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

请参阅Angular 2路由器事件侦听器

在Angular2 Rc1中,您可以注入RouteSegment,然后将其传递给.navigate()方法:

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


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

角2 rc2

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

新的V3路由器有一个url属性。

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

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

原始答案(RC版本)

我在AngularJS谷歌群组上找到了一个解决方案,它很容易!

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

这是最初的答案

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

角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){


}

在path FromRoot的帮助下,您可以获取父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/路由中获取参数,以下是演示片段

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

使用Angular2.2.1(在基于Angular2-webpack的项目中)工作如下:

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属性。因此,我们在变量中捕获该值,并且我们也可以在超文本标记语言页面中使用该变量。例如,我想仅在用户在主页上时显示div。在这种情况下,我的路由器URL值将是/home。所以我可以按以下方式编写div:

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

这很简单,在角度2中,您只需要像这样导入路由器库:

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 === "/搜索”

否则请执行以下操作

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的一个实例

方式1:使用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);
}
}

方式2Window.location我们在Javascript中做的,如果你不想使用路由器

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


我遇到的问题是,当用户是通过应用程序导航访问URL(或在特定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);
}

要获得当前路由器角度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());
}

这适用于如果你正在使用它与一个认证守卫

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内访问当前路由时,接受的答案不起作用,因为路由尚未完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只想从这里复制粘贴,这是我的解决方案:

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