“Circular dependency detected” in Angular 11, how to solve it?

Shubham
2 min readMay 8, 2021
Circular Dependency in Angular

Problem

We have one service named SharedService and a component named LoginDialogComponent.

SharedService contains all shared code in the application like Login BE call & functions to show login dialog after some period of time. (showLoginDialog())

In this case, our code will be like this:

In this scenario, we are using SharedService in LoginDialogComponent and LoginDialogComponent in SharedService. This one is a circular dependency.

In some scenarios, we can duplicate the required code and solve circular dependency. Or we can create a new service and move that code to that new service to avoid circular dependency.

Circular dependency error

WARNING in Circular dependency detected:

src\app\login-dialog\login-dialog.component.ts -> src\app\services\shared.service.ts -> src\app\login-dialog\login-dialog.component.ts

WARNING in Circular dependency detected:

src\app\services\shared.service.ts -> src\app\login-dialog\login-dialog.component.ts -> src\app\services\shared.service.ts

: Compiled successfully.

Solution

In this scenario to avoid circular dependency, we can not use SharedService’s injected object in LoginDialogComponent.

LoginDialogComponent’s code will be like this & we will assign sharedService’s object from SharedService like this:

Here “this” means the current instance of SharedService.

So after this small change, the application will work as expected without circular dependency error.

Thank You :) !!!

“📚 Enjoyed this article? Click the ‘Follow’ button to stay updated with my latest work. Thank you for being part of my Medium community! 📝✨ #WritingCommunity #FollowMe #Angular”

--

--