首页 文章

获取没有参数的当前路线

提问于
浏览
9

我需要在Angular 2中获得没有params的当前路由,我找到了一种方法来获取当前路径的params,如下所示:

this.router.url

然后分开它:

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

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

7 回答

  • -1

    parseTree 来自 Router 有助于在不了解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('/');
    

    从这里开始 . 如果您有二级插座根据需要进行调整 .

  • -3

    这可以帮助你:

    • 导入路由器:
    import { Router } from '@angular/router';
    
    • _1526345中的签名:
    constructor(private _router: Router) {}
    
    • 检查 _router events属性:
    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
            });
    
  • 0

    在我的情况下,当需要通过 router.navigate 更改网址上的 :id 时,我需要比较之前的路线和新路线 . 因为我想要没有不同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
        }
    });
    
  • 0

    我使用locationStrategy就像接受答案但使用 .split() 方法 . LocationStrategy在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];
        }
    }
    

    您应该进行的另一件事是确保在尝试获取 locationStrategy.path() 之前正确初始化 <router-outlet> . 如果 <router-outlet> isn 't initialize any Angular services can' t正确返回URL和查询参数 .

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

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

    但是在这种情况下,您会在每次路由器更改时触发您的功能,因此如果不需要,您需要保护此情况 .

  • 16

    这些都不适合我 .

    有很多方法,但在这种情况下,有一个警卫来阻止用户访问特定的URL . 这工作正常,除非URL有参数,因为传递的URL总是包含所有参数 .

    E.G: 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> { ... }
    
  • 0

    要获取没有查询参数的当前路由,可以使用下面提到的单行 . this.router.url.split( '?')[0]

  • 1

    更短的语法是使用@ angular / common中的LocationStrategy类来直接从浏览器的URL表示和读取路由状态,这比在具有多个Angular应用程序的情况下尝试获取路由器URL时更方便this.router.url模块 .

    import {LocationStrategy} from '@angular/common';
    
    
    export class MyComponent implements OnInit {
    
        constructor(private url:LocationStrategy) { }
    
        ngOnInit() {
              //this will log the current url
            console.log(this.url.path());
        }
    
    }
    

    然后使用 .split('?') 来获得最终结果 .

相关问题