Angular 2-如何在应用程序组件中获取当前网址

Tha*_*yen 5 angular2-routing angular

我正在尝试获取应用程序的当前URL,AppComponent但它始终返回根路径/。例如,如果我/users在新标签页中访问,则预期结果应为/users,但是当我在控制台中签入时,显示 /

但是,当我在子组件中执行相同操作时,它会起作用。下面是我的代码:

import {Component} from '@angular/core'
import {ActivatedRoute, Router} from '@angular/router'

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['app.component.scss'],
})

export class AppComponent {
    constructor(router: Router) {    
        console.log(this.router.url) // return '/'    
    }
}
Run Code Online (Sandbox Code Playgroud)

那怎么可能?

Pen*_*gyy 11

您可以订阅router.events和过滤NavigationEnd事件以获取当前活动的路由 url。

this.router.events.subscribe((e) => {
  if (e instanceof NavigationEnd) {
    console.log(e.url);
  }
});
Run Code Online (Sandbox Code Playgroud)

提到如果没有定义有效的路由器,这将失败。


Obj*_*eTC 5

在Angular 4中,您可以使用Location模块从app.component.ts中获取完整路径字符串

例如,在浏览器中,当您导航到“ http://yoursite.com/products/cars?color=red&model=202 ”时,下面的代码将输出pathString“ / products / cars?color = red&model = 202”。

在app.component.ts中

import { Component } from '@angular/core';
import { Router} from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';

    constructor(
    private location: Location
  ) { 
      var pathString = location.path();
      console.log('appComponent: pathString...');
      console.log(pathString);       
  }
}
Run Code Online (Sandbox Code Playgroud)

*信用:https : //tutorialedge.net/post/typescript/angular/angular-get-current-route-location/