Advertisement
fabiobiondi

Angular 5 interceptor - DI issue and solution

Nov 4th, 2017
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. // DOES NOT WORK
  2. @Injectable()
  3. export class AuthInterceptor implements HttpInterceptor {
  4.  
  5. constructor(
  6. private router: Router, private auth: Auth
  7. ) {}
  8.  
  9. intercept( req: HttpRequest<any>, next: any ): Observable<HttpEvent<any>> {
  10. const copiedReq = req.clone({
  11. headers: req.headers.set(
  12. 'authorization', 'Bearer ' + this.auth.getToken()
  13. )
  14. });
  15. return next.handle(copiedReq);
  16. }
  17. }
  18.  
  19. // RUNTIME ERROR
  20. compiler.js:19387 Uncaught Error: Provider parse errors:
  21. Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
  22.  
  23. --------
  24. WORKING EXAMPLE
  25.  
  26. @Injectable()
  27. export class AuthInterceptor implements HttpInterceptor {
  28.  
  29. constructor( private injector: Injector, private router: Router) {}
  30.  
  31. intercept( req: HttpRequest<any>, next: any ): Observable<HttpEvent<any>> {
  32. const auth = this.injector.get(Auth);
  33. const copiedReq = req.clone({
  34. headers: req.headers.set(
  35. 'authorization', 'Bearer ' + auth.getToken()
  36. )
  37. });
  38. return next.handle(copiedReq);
  39. }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement