Get current route without parameters

落花浮王杯 提交于 2020-06-10 07:20:46

问题


I need to get my current route without params in Angular 2, I found a way to get the current route with params as follows:

 this.router.url

and then split it:

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

But this looks as workaround, I think there should be better way?


回答1:


parseTree from Router helps fetching the segments without any knowledge about url structure.

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('/');

Start from here. If you have secondary outlets adjust as required.




回答2:


To get current route without query parameters, you can use below mentioned single line:

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



回答3:


this could help you:

  1. Import Router:

    import { Router } from '@angular/router';
    
  2. Signature in the constructor:

    constructor(private _router: Router) {}
    
  3. Check the _router events property:

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



回答4:


I use locationStrategy like in accept answer but with .split() method. LocationStrategy work perfect in Angular 4 & Angular 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];
    }
}

One more things you should carry about is to be sure that your <router-outlet> is properly initialize before you try to get locationStrategy.path(). If <router-outlet> isn't initialize any Angular services can't return URL and query params properly.

To be sure that you location strategy is initialize you can use subscribe method like:

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

But in this case you trigger your function on each router change so you need to protect this case if it's unwanted.




回答5:


I had a similar requirement, depending on which route I used to get the component I wanted different outcomes.

I found that activatedRoute.routeConfig.path was a great option and made it easy for me to see which route had been used.

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



回答6:


Native javascript will work to split the url into logical parts. Check out the "location" (or window.location) object. For example, using location at the url https://example.com/pathname1/pathname2?queryParam1=1&queryParam2=2 yields

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'



回答7:


In my case I needed to compare the previous route and the new route, when changing only the :id on the url via router.navigate. Since I wanted the path without the different ids, I got the original path of the route:

/* 
    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
    }
});



回答8:


None of these worked for me.

There are many approaches to this, but in this case a guard was in place to stop users going to specific URL's. This worked fine except when URL's had parameters as the passed URL always contained all the parameters.

E.G: myPage/param1/param2

Or: myPage?param1=1&param2=2

In this case I'd want just myPage.

I coded the below, I don't like it, I'm sure it can be improved but haven't found anything else that works so far:

    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 comes from the implementation for CanActivate (or inject Router).

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


来源:https://stackoverflow.com/questions/42504809/get-current-route-without-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!