目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
您可以使用ActivatedRoute来获取当前路由器
原文答案(RC版)
我在AngularJS谷歌Group上找到了一个解决方案,非常简单!
ngOnInit() {
this.router.subscribe((url) => console.log(url));
}
这是最初的答案
https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ
其他回答
在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:
constructor(private router:Router,private segment:RouteSegment) {}
ngOnInit() {
this.router.navigate(["explore"],this.segment)
}
下面是我在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"
}
数据是一个对象,我们需要该对象中包含的url属性。所以我们在变量中获取这个值,我们也可以在HTML页面中使用这个变量。例如,我想显示一个div仅当用户在主页上。在这种情况下,我的路由器url值将是/home。所以我可以用下面的方式写一个div:
<div *ngIf="location == '/home'">
This is content for the home page.
</div>
方法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);
}
}
方法二:窗口。如果你不想使用路由器,就像我们在Javascript中做的那样
this.href= window.location.href;
这很简单,在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
});
获取路由段:
import { ActivatedRoute, UrlSegment } from '@angular/router';
constructor( route: ActivatedRoute) {}
getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }