Is it possible to inject a service inside another service and vice versa at the same time?

前端 未结 3 1898
日久生厌
日久生厌 2021-01-18 06:28

I have a real scenario in a real project where I need 2 services to access the properties and/or methods of each other. I\'m not an Angular expert so is it possible?

相关标签:
3条回答
  • 2021-01-18 06:47

    AngularJS does not allow injection of circular dependencies.

    Miško Hevery, one of the authors of AngularJS, recommends finding the common elements:

    +---------+      +---------+
    |    A    |<-----|  B      |
    |         |      |  |  +-+ |
    |         |      |  +->|C| |
    |         |------+---->| | |
    |         |      |     +-+ |
    +---------+      +---------+
    

    And extracting it to a third service:

                             +---------+
    +---------+              |    B    |
    |    A    |<-------------|         |
    |         |              |         |
    |         |    +---+     |         |
    |         |--->| C |<----|         |
    |         |    +---+     +---------+
    +---------+
    

    For more information, see Circular Dependency in constructors and Dependency Injection by Miško Hevery.

    0 讨论(0)
  • 2021-01-18 07:07

    I agree with the solution proposed by basarat. Another workaround would be to initialize the instances outside DI and provide them as value like

    One service needs to be modified to be able to create an instance without providing the other service as dependency:

    @Injectable()
    export class FirstService {
    
      foo: string = 'abc';
      secondService: SecondService
    
      constructor() {
        //this.foo = this.foo + this.secondService.bar;
      }
    
      init(secondService:SecondService) {
        this.foo = this.foo + secondService.bar;
      }
    }
    

    Then create the instances imperatively and provide them as value

    let firstService = new FirstService();
    let secondService = new SecondService(firstService);
    
    @Component({
      selector: 'my-app',
      template: '<h1>Hello world!</h1>',
      providers: [
        provide(FirstService, {useFactory: () => {
          firstService.init(secondService);
          return firstService;
      }}), provide(SecondService, {useValue: secondService})]
    })
    ...
    

    Plunker example

    0 讨论(0)
  • 2021-01-18 07:11

    I'm not an Angular expert so is it possible

    No. Circular dependencies are not resolved by angular's DI.

    Also even systems that do support it, quite commonly are inconsistent e.g. commonjs https://nodejs.org/docs/latest/api/modules.html#modules_cycles will give you an empty object for a while.

    Solution

    Consider combining the two services into one. You can still move certain stuff (e.g. simple functions etc) out from the combined service if it becomes too much.

    0 讨论(0)
提交回复
热议问题