Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check angular route path from interceptor

I have a route path configured as:

{
    path: 'user/:id/edit/:type',
    component: UserEditTypeComponent,
},

I want to reach the path from the interceptor which i could access from activated routes as:

constructor(private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
    console.log(this.activatedRoute.routeConfig.path);
}

This results in returning this path user/:id/edit/:type in the console.

I want to get the same path from interceptor which i have tried as:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let ar = this.injector.get(ActivatedRoute);
    console.log(ar.routeConfig.path);
}

this returns error as: Cannot read property 'path' of null. I have removed the path and tested and found routeConfig to be null.

How do we get the activated route inside the interceptor?

Is there any other method to access the path in interceptor?

If the question seems to be unclear could updated it with more information.

like image 279
PaladiN Avatar asked Apr 09 '18 11:04

PaladiN


4 Answers

I got it to work like this after peeking in the implementation

constructor(private router: Router) {
   console.log(this.router.routerState.snapshot.url);
} 

This will give you the whole url with params and everything. Like: user/234?hasName=true&hasShoes=false

like image 55
Utukku Avatar answered Oct 19 '22 07:10

Utukku


I know this is a little late.. but following will resolve your problem, had similar concerns..

constructor(private activatedRoute: ActivatedRoute) {
    console.log(activatedRoute.snapshot['_routerState'].url);
} 

activatedRoute.snapshot['_routerState'].url will contain your /user/:id/edit/:type.

like image 35
yanky_cranky Avatar answered Oct 19 '22 07:10

yanky_cranky


If in the interceptor the activated route and the snapshot aren't loaded with the current path or url, as a last choice, you could use the classic window.location

like image 39
Javi Avatar answered Oct 19 '22 05:10

Javi


The best way to do this is to do it through the router object:

constructor(private router: Router) {
    console.log(this.router.routerState.snapshot);
} 

This way you don't have to access hidden properties.

like image 1
Iván García García Avatar answered Oct 19 '22 07:10

Iván García García