2017-06-19 89 views
1

我試圖在AppComponent中獲取當前應用程序的url,但它始終返回根路徑/。例如,如果我在新選項卡中訪問/users,預期結果應該是/users,但是當我登入控制檯時,它會顯示 /Angular 2 - 如何獲取應用程序組件中的當前url

但是,它在我在子組件中做同樣的工作。以下是我的代碼:

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 '/'  
    } 
} 

這怎麼可能?

回答

2

如果您想獲取當前網址,請改爲使用ActivatedRoute。 在構造函數中添加像這樣

constructor(
private router: Router, 
private route: ActivatedRoute) {  
    route.params.subscribe(p => { 
     //let's say you want to get id parameter. 
     console.log(p['id']); 
    }); 
    } 
+0

還可以比較:'this.route.snapshot.params [ '身份證']',甚至'this.route.snapshot .paramMap.get( 'ID')'。 – developer033

-3

你遞歸迭代parent屬性,直到你達到相當於您的應用程序的根最上方的元素。

3

您可以訂閱router.events並過濾NavigationEnd事件以獲取當前活動路由網址。

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

提到這將失敗,如果這不是有效的路由器定義。

+0

是的!如果您試圖從app.component(或爲該路由定義的模塊的父節點的任何其他組件)獲取完整路由+參數,則可以觀察「NavigationEnd」事件。例如,我有一個路徑'/ product/category /:id',我需要從我的'產品模塊'之外的'導航欄組件'中標識這個。使用@ Pengyy的解決方案,我現在可以看到在瀏覽器中輸入的確切路徑:'/ product/cars/1'。 – ObjectiveTC

+0

注意 - 爲了我的目的,我最終使用[RouterLinkActive]爲我的導航按鈕分配了「活動」css類。但是,如果您需要來自父模塊的路由,請使用@ Pengyy的解決方案用於任何其他目的。 – ObjectiveTC

2

在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);  
    } 
} 

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

+0

這樣做的一個好處是,在加載任何子模塊之前,完整路徑是可用的。因此,如果您使用全局變量來保存狀態枚舉器,那麼您可以讀取該變量以在加載子模塊時對其進行配置。 – ObjectiveTC

相關問題