代码之家  ›  专栏  ›  技术社区  ›  khush

如何在Angular4+中获取Url路径,并将其与用于检查访问的参数进行匹配?

  •  2
  • khush  · 技术社区  · 6 年前

    网址: http://localhost:4200/#/users/company/5263/12

    我已在我的用户详细信息中添加了此路由-路由.module.ts

    {
        path: "company/:companyId/:userId"
        component: UserDetailsComponent,
        canActivate: [AdminGuard]
    }
    

    现在我需要这个值在我的保护文件

        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> | boolean {
            this.loaderService.show();
            let url: string = state.url;  
            // Here I need that value
            return true;        
        }
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   Aarsh    6 年前

    import {Router, ActivatedRoute, Params} from '@angular/router';
    import {OnInit, Component} from '@angular/core';
    
    @Component({...})
    export class MyComponent implements OnInit {
    
      constructor(private activatedRoute: ActivatedRoute) {}
    
      ngOnInit() {
           let url =   this.activatedRoute.snapshot._routerState.url
           let urlSegment = this.activatedRoute.snapshot.routeConfig.path
    
    
      }
    
    }
    

    我有这个网址: http://localhost:4200/product/productDetails/79

    希望这能奏效。

        2
  •  1
  •   khush    6 年前

    i、 e.用户/公司/:公司ID/:用户ID

      const index = state.url.lastIndexOf(route.pathFromRoot[route.pathFromRoot.length - 1].routeConfig.path.split('/')[0]);
      url = state.url.substring(0, index) + route.pathFromRoot[route.pathFromRoot.length - 1].routeConfig.path;
      // url = users/company/:companyId/:userId
    

    希望这有帮助。