Проблема в круговой зависимости. AuthenticationService
нужно HttpClient
, HttpClient
нужно Interceptors
, ErrorInterceptor
нужно AuthenticationService
.
Чтобы решить эту проблему, вам нужно разделить AuthenticationService
на два слоя - один для храненияданные аутентификации и один для связи API.
class AuthenticationStore {
storeData(authData) {}
getData(): AuthData {}
clearData() {}
Скажем, у вас есть AuthenticationStore
. Тогда ErrorInterceptor
будет использовать AuthenticationStore
вместо AuthenticationService
.
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationStore: AuthenticationStore) {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationStore.clearData();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
Или вы можете использовать инжектор, это немного более грязное решение.
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
const authenticationService = this.injector.get(AuthenticationService);
authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}