Home > database >  Angular use functions 2 ways within Libs
Angular use functions 2 ways within Libs

Time:12-17

I have a question I have generated 2 Libs in Angular. Lib 1 wants to use an exported function of Lib 2. But lib 2 also wants to use an exported function of lib 1. When i try to do this angular gets stuck because of circular dependency is there a way to fix this?

Thx a lot

CodePudding user response:

Assuming you have 2 Services:

export class Service1 {
    constructor(private readonly m_service2: Service2){}
    doSomething(){ this.m_service2.doSomething(); }
}

export class Service2 {
    constructor(private readonly m_service1: Service1){}
    doSomething(){ this.m_service1.doSomething(); }
}

This is a typical circular dependency conflict.

To solve it, you can create another service Service3, which holds the function doSomething and is injected into the other services.

export class Service1 {
    constructor(private readonly m_service3: Service3){}
    doSomething(){ this.m_service3.doSomething(); }
}

export class Service2 {
    constructor(private readonly m_service3: Service3){}
    doSomething(){ this.m_service3.doSomething(); }
}

export class Service3 {
    doSomething(){ /* do something */ }
}
  • Related