What is circular dependency in angular?
Circular dependency occurs when service A injects service B, but service B in turn injects service A, usually indirectly. For example, B depends on service C which depends on A – A -> B -> C -> A forms a circle.
The simplest scenario is if we have three files:
forms.model.ts
import { CustomModel } from './custom.model';
import { CustomForm } from './custom.form';
export class Forms {
items: CustomForm[] = [];
public constructor(models?: CustomModel[]) {
models.forEach(model => this.items.push(new CustomForm(model)));
}
}
custom.model.ts
export class CustomModel {
nestedModels: CustomModel[];
}
custom.form.ts
import { Forms } from './forms.model';
import { CustomModel } from './custom.model';
export class CustomForm {
nestedForms: Forms;
constructor(model: CustomModel) {
this.nestedForms = new Forms(model.nestedModels);
}
}
This causes the following warnings:
WARNING in Circular dependency detected:
srcppmodelscustom.form.ts -> srcppmodelsorms.model.ts -> srcppmodelscustom.form.ts
WARNING in Circular dependency detected:
srcppmodelsorms.model.ts -> srcppmodelscustom.form.ts -> srcppmodelsorms.model.ts
The issue is clear:
We are using custom.model.ts into custom.form.ts and also custom.form.ts into custom.model.ts. This is called CircularDependencies and that is not good. Circular Dependency can result in a crash of an application. We should definitely remove circular dependency present in codebase.
Solution:
Just remove import { CustomForm } from './custom.form'; from custom.model.ts