khush
khush

Reputation: 2799

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

Component: UserDetailsComponent

I have added this route in my user-details-routing.module.ts

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

Now I need this below value in my Guard file

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

Upvotes: 2

Views: 305

Answers (2)

khush
khush

Reputation: 2799

I got my full routing url

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

by following line of code,

  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

Hope this helps.

Upvotes: 1

Aarsh
Aarsh

Reputation: 2595

You can get query params like this using ActivatedRoute and then store it in one variable. Here is the example :

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


  }

}

I have this url :::: http://localhost:4200/product/productDetails/79

My output of url is Like this ::: "/product/productDetails/79"

My output of urlSegment is Like this ::: "productDetails/:id"

Hope this will work.

Upvotes: 4

Related Questions