When you have two services initialized in each other’s constructor, you get a Circular Dependency Error like below:
In order to fix this error, you need to break this dependency by refactoring your code.
Example
Suppose you have two services, UserService
and AuthService
. The error is triggered in the following way:
UserService
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class UserService {
constructor(private _authService: AuthService){}
saveUserToken() {
localStorage.setItem('token', this._authService.userToken());
}
}
AuthService
import { UserService } from './user.service';
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private _userService: UserService){}
userToken() {
return 'dgf435tfdeg43565hrf4657jghj789i7869khj879gfdg4e543gfdeg435643ghfer';
}
}
Let’s refactor the method getUserToken
in UserService so that we don’t need to import AuthService
in UserService
:
UserService
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class UserService {
constructor(){}
saveUserToken(userToken: string) {
localStorage.setItem('token', userToken);
}
}
Also, notice that both service classes have the following decorator:
@Injectable({
providedIn: 'root',
})
This means that they initialized once globally in the app (Singleton). If they both rely on each other as in the initial case, this presents a problem for Angular: Which service class should be initialized first: UserService
or AuthService
? Therefore, refactoring as we did above will solve this issue and avoid encountering a Circular Dependency Error.