angulardependency-injectioncircular-dependency

Angular circular dependency - Components call each other


In my Angular App, I have 2 Components that can open each other as modals. From component A you can open component B, and from component B you can open component A. How can I achieve this without having a circular dependency? I tried moving the modal calls to a service, but both components need this service injected and I have the circular dependency again.

I also read something about injecting with forwardRef, but I could not get it to work. I tried to inject the service like this in the constructor of the components:

@Inject(forwardRef(() => CircularService)) private circularService: CircularService

Solution

  • i have a solution for your problem, we can use InjectionTokens and provide them in a shared Module. First component token: component-a-token.ts

    export const COMPONENT_A_TOKEN = new InjectionToken<any>('ComponentAToken');
    

    Second component token: component-b-token.ts

    export const COMPONENT_B_TOKEN = new InjectionToken<any>('ComponentBToken');
    

    Then provide components in module:

     providers: [
            RenderService,
            { provide: COMPONENT_A_TOKEN, useValue: ComponentA },
            { provide: COMPONENT_B_TOKEN, useValue: ComponentB}
        ]
    

    this allows us to inject components class:

    @Component({
        selector: 'app-a',
        templateUrl: './a.component.html',
        styleUrls: ['./a.component.scss']
    })
    export class ComponentA {
        constructor(@Inject(COMPONENT_B_TOKEN) private componentB) {
        }
    }