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

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


当前回答

方法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;

其他回答

在Angular 14中,如果你这样做

this.router.url

它总是会返回'/'

您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。

import { Location } from '@angular/common';

constructor(private location: Location) { }

ngOnInit(): void {
    console.log(this.location.path());  // returns path

}

这适用于与authguard一起使用的情况

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );

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

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

然后得到主出口的分段:

tree.root.children[PRIMARY_OUTLET].segments;

到目前为止,我的路径如下-

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

其中,路由器是ActivatedRoute的一个实例

你可以试试

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