我如何获取 Url 路径和参数以匹配它以检查 Angular4+ 中的访问?

How can I fetch the Url path with parameters for matching it to check access in Angular4+?

URL: http://localhost:4200/#/users/company/5263/12

组件:用户详细信息组件

我已经在我的用户详细信息中添加了这条路线-routing.module.ts

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

现在我的 Guard 文件中需要以下值

users/company/:companyId/:userId

admin.guard.ts

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> | boolean {
        this.loaderService.show();
        let url: string = state.url;  
        // Here I need that value
        return true;        
    }

您可以使用 ActivatedRoute 获取这样的查询参数,然后将其存储在一个变量中。这是示例:

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


  }

}

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

我的 url 输出是这样的 ::: "/product/productDetails/79"

我的url段输出是这样的::: "productDetails/:id"

希望这会奏效。

我得到了完整的路由 url

i.e. users/company/:companyId/:userId

通过以下代码行,

  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

希望对您有所帮助。