Seeing “NG0200: Circular dependency in DI detected for …” in your Angular or Ionic app? This guide explains what the error means, how to find the loop between your services, and shows 5 fixes, including the classic HTTP interceptor and AuthService cycle.
Your app compiles, but the page stays blank, and the browser console shows this:
ERROR Error: NG0200: Circular dependency in DI detected for AuthService.Find more at https://angular.dev/errors/NG0200
The class name in your message will be different, and some Angular versions print a slightly different text. The important part is the name after detected for. It is one of the classes that sits inside a loop.
What Does NG0200 Mean?
Angular creates services using dependency injection. When a service asks for another service in its constructor, Angular must create that other service first. A circular dependency happens when the chain leads back to where it started, so Angular can never finish creating anything:
ServiceAneedsServiceB, andServiceBneedsServiceA(a direct loop).AneedsB,BneedsC, andCneedsA(a longer loop).- An HTTP interceptor needs
AuthService, andAuthServiceneedsHttpClient, which needs the interceptors (the most common loop in real apps).
The error shows only one class from the loop, so your first job is to find the others.
Step 1: Find the Loop
Take the class name from the message and list everything it injects. Then check what those classes inject, and keep going until you return to the first class. Writing the chain on paper helps:
AuthService -> HttpClient -> HTTP_INTERCEPTORS -> AuthInterceptor -> AuthService
Also check these places that people forget:
- services used by
APP_INITIALIZERor other startup providers, - route guards and resolvers that inject a service which injects the
Routeror the same guard, - interceptors, since they are created together with
HttpClient, - services that use
inject()at field level, not only in the constructor.
A different problem looks similar: a circular file import in TypeScript, for example two files that import each other. That usually shows messages such as “Cannot access X before initialization”, not NG0200. If you suspect an import cycle, a tool such as madge can list them:
npx madge --circular --extensions ts src
Step 2: Move the Shared Logic Into a Third Service
The cleanest fix is to change the shape of the dependencies, from a loop to a triangle that points one way. Here is a typical loop:
@Injectable({ providedIn: 'root' })export class OrderService { constructor(private cart: CartService) {}}
@Injectable({ providedIn: 'root' })export class CartService { constructor(private orders: OrderService) {} // loop: Cart -> Order -> Cart}
If both services need the same piece of logic, extract it into a third service that depends on neither of them:
@Injectable({ providedIn: 'root' })export class PricingService { calculateTotal(items: Item[]): number { return items.reduce((sum, i) => sum + i.price * i.qty, 0); }}
@Injectable({ providedIn: 'root' })export class OrderService { constructor(private pricing: PricingService) {}}
@Injectable({ providedIn: 'root' })export class CartService { constructor(private pricing: PricingService) {}}
Now both services depend on PricingService, and nobody depends back. This is usually the sign of a better design too: shared rules live in one place.
Step 3: Fix the HTTP Interceptor and AuthService Loop
This is the loop that most Angular developers meet. A class-based interceptor needs the token from AuthService, and AuthService uses HttpClient to log in:
@Injectable()export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) {} // AuthService injects HttpClient: NG0200
intercept(req: HttpRequest<any>, next: HttpHandler) { const token = this.auth.token; return next.handle(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req); }}
The interceptor only needs the token, not the login logic. Move the token into a small service that has no HttpClient dependency:
@Injectable({ providedIn: 'root' })export class TokenService { get token(): string | null { return localStorage.getItem('access_token'); } save(token: string) { localStorage.setItem('access_token', token); } clear() { localStorage.removeItem('access_token'); }}
@Injectable()export class AuthInterceptor implements HttpInterceptor { constructor(private tokens: TokenService) {} // no loop any more
intercept(req: HttpRequest<any>, next: HttpHandler) { const token = this.tokens.token; return next.handle(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req); }}
AuthService can still use HttpClient and TokenService. The chain is now AuthService → HttpClient → AuthInterceptor → TokenService, which ends.
In Angular 15 and newer, a functional interceptor avoids many of these loops, because it asks for services when a request happens, and not when HttpClient is created:
import { HttpInterceptorFn } from '@angular/common/http';import { inject } from '@angular/core';
export const authInterceptor: HttpInterceptorFn = (req, next) => { const tokens = inject(TokenService); const token = tokens.token; return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);};
// register itprovideHttpClient(withInterceptors([authInterceptor]))
One warning: if your interceptor calls a service that makes its own HTTP request, for example a token refresh, that request passes through the interceptor again. Guard against that, or you get an endless loop of requests instead of NG0200.
Step 4: Ask for the Service Later With Injector
When you cannot restructure the code right now, you can break the loop by not requesting the second service in the constructor. Inject the Injector instead, and ask for the service at the moment you actually need it:
import { Injectable, Injector } from '@angular/core';
@Injectable({ providedIn: 'root' })export class CartService { constructor(private injector: Injector) {}
private get orders(): OrderService { return this.injector.get(OrderService); // created only when first used }
checkout() { this.orders.create(/* ... */); }}
This works because CartService no longer needs OrderService at creation time. Treat it as a bridge, not a goal. It hides the dependency from the constructor, so the next developer can no longer see it, and the loop still exists in your design. Add a comment that explains why you did it.
Step 5: Use Events Instead of Direct Calls
Sometimes two services call each other because one needs to tell the other that something happened. Replace the direct call with a stream that one service publishes and the other listens to:
@Injectable({ providedIn: 'root' })export class CartEvents { private readonly cleared = new Subject<void>(); readonly cleared$ = this.cleared.asObservable();
notifyCleared() { this.cleared.next(); }}
// CartService calls events.notifyCleared()// OrderService subscribes to events.cleared$ and reacts
Now CartService and OrderService both know CartEvents, but they do not know each other.
What Not to Do
- Do not use forwardRef to hide the error.
forwardRefsolves a different problem, a class that is used before it is defined in the file. It does not remove a real dependency loop. - Do not make a dependency optional to silence the message. That can leave you with
nullservices at runtime. - Do not keep the loop and hope that creation order works out. It breaks later, when someone changes an import or a provider.
Quick Diagnosis Table
| Situation | Best fix |
|---|---|
| Two services inject each other | Step 2: extract a third service |
| Interceptor needs AuthService, which needs HttpClient | Step 3: TokenService or a functional interceptor |
| You cannot refactor yet | Step 4: Injector with lazy get |
| One service only needs to notify another | Step 5: events |
| Error mentions an import or “before initialization” | Check TypeScript import cycles with madge |
Best Practices
- Keep services small, with one job. Large services that do everything are the usual source of loops.
- Let dependencies point in one direction: features depend on shared services, not the other way round.
- Keep state-only services free of HTTP and router dependencies.
- When you add a dependency to a service, ask what that service already depends on.
Conclusion
NG0200 means Angular found a loop while creating your services. Write down the chain, then break it by moving shared logic to a third service, keeping token handling separate from HTTP calls, or using events. Use the Injector trick only as a temporary bridge. A clear one-way dependency design is easier to test and maintain, and it keeps the error away.

0 Comments