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

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


当前回答

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

在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') { ... }
}

其他回答

将Location注入组件并读取Location .path(); 你需要在某个地方添加ROUTER_DIRECTIVES,这样Angular才能解析Location。你需要在这个模块中添加import: [RouterModule]。

更新

在V3 (RC.3)路由器中,您可以注入ActivatedRoute,并使用它的snapshot属性访问更多细节。

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

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

另见Angular 2的路由器事件侦听器

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

我面临的问题是,当用户在应用程序中导航或访问URL(或在特定URL上刷新)时,我需要URL路径来显示基于URL的子组件。

更重要的是,我想要一个可以在模板中使用的Observable,所以路由器。Url不是一个选项。和路由器。事件订阅,因为在组件模板初始化之前触发路由。

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => 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"
}

在组件文件中:

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

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

在路由文件中: