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.
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
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
.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With