如何获得当前路线

问题描述 投票:325回答:29

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

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

angular angular2-routing
29个回答
363
投票

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

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

9
投票

本机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);

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


6
投票

短版本,如果您导入路由器,那么您可以简单地使用一些东西

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的答案对我有帮助,这和他的答案相同,但有一些细节,因为它可能对某人有所帮助


5
投票

在Angular2 Rc1中,您可以注入RouteSegment并以naviagte方法传递它们。

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

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

5
投票

使用角度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的代码。


4
投票

角度2 rc2

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

4
投票

以下是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>

4
投票

我有同样的问题使用

this.router.url

我得到了查询参数的当前路由。我做的解决方法是使用它:

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

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


4
投票

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

原始答案(RC版)

我在AngularJS Google Group找到了一个解决方案,这很简单!

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

这是最初的答案

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


3
投票

为了您的目的,您可以使用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

3
投票

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

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

然后获得主要出口的部分:

tree.root.children[PRIMARY_OUTLET].segments;

114
投票

角度RC4:

你可以从Router进口@angular/router

然后注入它:

constructor(private router: Router ) {

}

然后调用它的URL参数:

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

3
投票

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

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


2
投票

这很简单,在角度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
            }); 

2
投票

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

WAY 2 Window.location就像我们在Javascript中所做的那样,如果你不想使用路由器

this.href= window.location.href;

1
投票

这可能是你的答案,使用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'];
        });
    }
}

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

1
投票

如果您需要访问当前网址,通常您必须等待NavigationEnd或NavigationStart执行某些操作。如果您只订阅路由器事件,则订阅将在路由生命周期中输出许多事件。相反,使用RxJS运算符仅筛选所需的事件。这有利的副作用是现在我们有更严格的类型!

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


1
投票

当用户浏览应用程序或访问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)
);

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


1
投票

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

0
投票

在组件文件中:

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

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

在路由文件中:

enter image description here


0
投票

您可以在.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
      }
    });

51
投票

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 router event listener


36
投票

对于新路由器> = 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"
}

25
投票

对于那些仍在寻找这个的人。在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

24
投票

获取路线段:

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

constructor( route: ActivatedRoute) {}

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

18
投票

用这个

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

constructor(private router: Router) {
    router.events.filter((event: any) => 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: any) => event instanceof NavigationEnd)
)
    .subscribe(event => {
        console.log(event);
    });

12
投票

你可以试试

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给出路径名称。


10
投票

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

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.url);
    }
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.