cyclic dependency. HttpInterceptor and TranslateService
Asked Answered
F

0

3

This is discussed a lot, but I can't find how to solve my issue.

The reason is clear, I'm trying to use translateService in my interceptor, but both depends on httpClient.

I only happens when my interceptor constructor is:

  constructor(    
    private router: Router,
    private translate: TranslateService){}

If I remove translate it doesn't fails because of cyclic dependency.

So, I guess I need to access to translate in some different way but I can't find it.

How can I do it?

I tried the links suggestions, finally I got it.

constructor(    
private router: Router,
private injector: Injector){
  const translate =  injector.get(TranslateService);
}


intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     //intercept method and:
   .catch(err => this.handleError(err));

}


private handleError(error): Observable<any> {

if (error.status === 401) {
  this.router.navigate(['/login']);
} else if (error.status === 403) {
  this.router.navigate(['/unauthorized']);
} else {
   this.injector.get(TranslateService).get(['GENERIC_ERROR', 'OK'])
}
return Observable.throw(error);

}

Fanlight answered 22/1, 2018 at 7:32 Comment(5)
provide TranslateService under providers in NgModuleHomeopathic
Please, update the question with how exactly you use the service there.Karlenekarlens
Possible duplicate of angular 4.3x dynamic http interceptorKarlenekarlens
to avoid circular dependency try use injector, see, e.g. #37482960 but you can re-think your code.Spence
edit with suggestionsFanlight

© 2022 - 2024 — McMap. All rights reserved.