Why ActivatedRoute params are null inside http interceptor?

Viewed 258

I am trying to send a route parameter in the header of my request to the api with and interceptor. for that i injected the activatedRoute service into a custom interceptor, not sure why the params are null?

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private activeRoute: ActivatedRoute) {
    console.log(this.activeRoute.snapshot.params.itemGuid); //Undefined
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = sessionStorage.getItem('sessionToken');
    let newHeaders = req.headers;
    if (token) {
      newHeaders = newHeaders.append('sessionToken', token);
    }

    const authReq = req.clone({ headers: newHeaders });

    return next.handle(authReq);
  }
}

AppModule.ts

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true,
    }
  ],

Null activatedRoute parameters

If I try this, it works

enter image description here

Any idea why is this happening and I can get the params directly?

I am using angular 8

1 Answers

It depends on the place where you inject the ActivatedRoute service.

ActivatedRoute is a a service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params, and the global fragment

We can get the queryParams or fragment but ActivatedRoute provides path param info only to the corresponding route component.

Related