我在一个真实的项目中有一个真实的场景,我需要2个服务来访问彼此的属性和/或方法.我不是Angular专家所以它可能吗?
我试过了,它失败了.这是我的尝试:
app.component.ts
import { Component } from '@angular/core'; import { FirstService } from './first.service'; import { SecondService } from './second.service'; @Component({ selector: 'my-app',template: '<h1>Hello world!</h1>',providers: [FirstService,SecondService] }) export class AppComponent { constructor(public firstService: FirstService,public secondService: SecondService) { console.log(firstService.foo); console.log(secondService.bar); } }
first.service.ts
import { Injectable } from '@angular/core'; import { SecondService } from './second.service'; @Injectable() export class FirstService { foo: string = 'abc'; constructor(public secondService: SecondService) { this.foo = this.foo + this.secondService.bar; } }
second.service.ts
import { Injectable } from '@angular/core'; import { FirstService } from './first.service'; @Injectable() export class SecondService { bar: string = 'xyz'; constructor(public firstService: FirstService) { this.bar = this.bar + this.firstService.foo; } }
Plunker:http://plnkr.co/edit/PQ7Uw1WHpvzPRf6yyLFd?p=preview
只是将第二个服务注入第一个服务工作正常,但是一旦我将第一个服务注入第二个服务,它就会失败并向控制台抛出错误.
那有什么不对?
abcxyz xyzabc
提前致谢!
AngularJS不允许注入循环依赖.
AngularJS的作者之一MiškoHevery建议找到共同的元素:
+---------+ +---------+ | A |<-----| B | | | | | +-+ | | | | +->|C| | | |------+---->| | | | | | +-+ | +---------+ +---------+
并将其提取到第三个服务:
+---------+ +---------+ | B | | A |<-------------| | | | | | | | +---+ | | | |--->| C |<----| | | | +---+ +---------+ +---------+
有关更多信息,请参阅MiškoHevery的Circular Dependency in constructors and Dependency Injection.