获取无参数的当前路线



我需要在Angular 2中获取当前的路线,而我找到了一种使用参数的当前路线的方法:

 this.router.url

然后将其分开:

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

但这看起来像解决方法一样,我认为应该有更好的方法?

要获取当前路由而无需查询参数,您可以使用下面提到的单行:

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

parseTree的 CC_1有助于获取段,而无需任何有关URL结构的知识。

import { Router } from '@angular/router';
...
constructor(private router: Router) {}
...
const urlTree = this.router.parseUrl(url);
const urlWithoutParams = urlTree.root.children['primary'].segments.map(it => it.path).join('/');

从这里开始。如果您根据需要调整次要插座。

对我来说,这是我设法做的最干净的解决方案。我希望它有帮助

import { Router } from '@angular/router';
    
constructor(private router: Router){}
getUrlWithoutParams(){
   let urlTree = this.router.parseUrl(this.router.url);
   urlTree.queryParams = {}; 
   urlTree.fragment = null; // optional
   return urlTree.toString();
}

简短而简单的纯js。

location.pathname

本机JavaScript将有效地将URL分为逻辑部分。查看"位置"(或Window.location)对象。例如,使用url https://example.com/pathname1/pathname2?queryparam1=1& queramparam2=2产生

的位置
location.origin === 'https://example.com/pathname1/pathname2'
location.href === 'https://example.com/pathname1/pathname2?queryParam1=1&queryParam2=2'
location.pathname === '/pathname1/pathname2'
location.search === '?queryParam1=1&queryParam2=2'

如果您使用的是 webpack ,则可以使用捆绑在一起的url polyfill 模块以及Angular Router模块。<<<<<<<<<<<<<<<<<<<<<<<<

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as url from 'url'
@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  public constructor(public readonly router: Router) {}
  public ngOnInit() {
    const urlInfo = url.parse(this.router.url)
    console.log(urlInfo.pathname)
  }
}

我也有类似的要求,具体取决于我用来获得我想要不同结果的组件的路线。

我发现activatedRoute.routeConfig.path是一个不错的选择,使我很容易看到使用了哪种路线。

constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
  if (this.activatedRoute.routeConfig.path === 'heroes/:id')

这可以帮助您:

  1. import 路由器

    import { Router } from '@angular/router';
    
  2. 构造函数中的签名

    constructor(private _router: Router) {}
    
  3. 检查 _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
            }); 
    

要获取当前路由而无需查询参数,您可以使用下面提到的单行:

this.url = this.url.substr(0, this.url.lastIndexOf("?"));

这对我来说就像魅力:

  currentUrl: string;
  constructor(private router: Router) {}
  ngOnInit() {
    const urlTree: UrlTree = this.router.parseUrl(this.router.url);
    const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children['primary'];
    this.currentUrl = urlSegmentGroup ? urlSegmentGroup.segments.map((it) => it.path).join('/') : '';
  }

在我的情况下,我需要比较上一个路线和新路线,当在URL上仅更改:id :iD 通过 router.navigate 。由于我想要没有不同ID的路径,所以我得到了路线的原始路径:

/* 
    Routes = [
        { path: 'main/details/:id', component: DetailComponent }
    ]
    previousRoute = '/main/details/1'
    newRoute      = '/main/details/2'
*/
this.routeSubscription = this.router.events.filter((event) => event instanceof ResolveStart)
                                           .pairwise() // returns previous and current events
                                           .subscribe((ev: [ResolveStart, ResolveStart]) => {
    let sameRoute = ev[0].state.root.firstChild.routeConfig.path == ev[1].state.root.firstChild.routeConfig.path ?
                       ev[0].state.root.firstChild.routeConfig.path : undefiend;
    if (sameRoute) {
        // Same routes, probably different ids 
        console.log(sameRoute) // gives 'main/details/:id'
    } else {
        // Different routes
    }
});

我使用locationstrategy在接受答案中,但使用 .split()方法。位置策略在Angular 4&amp;角5;

import {LocationStrategy} from '@angular/common';
export class MyService {
    constructor(private locationStrategy: LocationStrategy) {
    }
    public getUrl(filters: FilterConfig[]): void {
        const url = this.locationStrategy.path();
        const urlArray = url.split('?');
        return urlArray[0];
    }
}

您还应该携带的一件事是确保您的<router-outlet>在尝试获得locationStrategy.path()之前正确初始化。如果<router-outlet>没有初始化任何Angular Services无法正确返回URL并查询参数。

要确保您的位置策略初始化,您可以使用订阅方法:

this.router.events.subscribe((evt) => {
...
}

但是,在这种情况下,您在每个路由器上触发功能,因此如果不需要,则需要保护此情况。

这些都不适合我。

有很多方法,但是在这种情况下,有一个警卫可以阻止用户进入特定URL。这效果很好,除非URL具有参数,因为传递的URL始终包含所有参数。

例如: myPage/param1/param2

或:myPage?param1=1&param2=2

在这种情况下,我只想 myPage

我对下面的编码进行了编码,我不喜欢它,我敢肯定它可以得到改进,但还没有找到任何其他可行的方法:

    let url: string = state.url;
    let urlParams: string[];
    if (url.includes("?")) {
        url = url.substr(0, url.indexOf('?'));
    } else {
        urlParams = route.url.toString().split(';')[0].split(',');
        if (urlParams.length > 1) {
            urlParams.shift(); // Remove first element which is page name
            // Get entire splitting on each param
            let fullUrlSegments: string[] = state.url.split('/');
            // Remove number of params from full URL
            fullUrlSegments = fullUrlSegments.slice(0, fullUrlSegments.length - urlParams.length);
            url = fullUrlSegments.join('/');
        }
    }
    alert(url);

state.url来自CanActivate的实现(或注入Router)。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) Observable<boolean> { ... }

您可以使用url https://developer.mozilla.org/en-us/docs/web/api/url/url/url/url/url

const url = new URL("https://example.org/route/test?test")
const path = url.origin + url.pathname

,但在Internet Explorer中不起作用。

使用Angular PlatformLocation

@Component{...}
// or
@Service{...}
export class Some {
constructor(private platformLocation: PlatformLocation) {
  console.log(this.platformLocation.pathname);
}

最新更新