目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
方法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;
其他回答
可以在.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
}
});
你可以使用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
在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:
constructor(private router:Router,private segment:RouteSegment) {}
ngOnInit() {
this.router.navigate(["explore"],this.segment)
}
给那些还在寻找这个的人。在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 2.2.1中(在一个基于angar2 -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的代码。