在我的Angular 2应用程序中,我有两个相互依赖的服务(来自服务B的服务A调用方法,反之亦然).以下是相关代码:在app.component.ts中:
import {Component} from 'angular2/core';
import {TempService} from '../services/tmp';
import {Temp2Service} from '../services/tmp2';
@Component({
selector: 'my-app',
templateUrl: 'app/app/app.component.html',
providers: [TempService, Temp2Service]
})
export class AppComponent { (...) }
Run Code Online (Sandbox Code Playgroud)
服务1:
import {Injectable} from 'angular2/core';
import {Temp2Service} from './tmp2';
@Injectable()
export class TempService {
constructor (private _sessionService: Temp2Service) {}
}
Run Code Online (Sandbox Code Playgroud)
服务2:
import {Injectable} from 'angular2/core';
import {TempService} from './tmp';
@Injectable()
export class Temp2Service {
constructor (private _sessionService: TempService) {}
}
Run Code Online (Sandbox Code Playgroud)
运行该应用程序会导致以下错误:
EXCEPTION:无法解析'Temp2Service'的所有参数(未定义).确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且'Temp2Service'使用Injectable进行修饰
在其中一个服务中评论构造函数时,应用程序运行正常.所以我的猜测是两个服务的"交叉引用"导致了这个问题.你知道这里出了什么问题吗?或者我的方法已经错了?
谢谢你的建议!
Mar*_*tin 34
这是一种称为循环依赖的.这不是Angular2本身的问题.我所知道的任何语言都不允许这样做.
您将需要重构代码以删除此循环依赖项.您可能需要将其中一项服务拆分为新服务.
在你遵循单一的负责任原则,你会发现你不会进入循环依赖陷阱.
Gün*_*uer 28
构造函数注入可防止循环依赖.
它可以通过注入Injector和请求依赖性来分解,例如:
private payrollService:PayrollService;
constructor(/*private payrollService:PayrollService*/ injector:Injector) {
setTimeout(() => this.payrollService = injector.get(PayrollService));
}
Run Code Online (Sandbox Code Playgroud)
另请参见循环依赖注入角度2
Cha*_*son 17
这里的关键不是通过构造函数注入服务,而是使用显式setter和getter.我会在Angular 4中使用以下模式:
app.component.ts
import { FooService } from './foo/foo.service';
import { BarService } from './bar/bar.service';
export class AppComponent {
constructor(public fooService: FooService, public barService: BarService) {
this.fooService.setBarService(barService);
}
}
Run Code Online (Sandbox Code Playgroud)
foo.service.ts
@Injectable()
export class FooService {
barService: any;
constructor(){
}
setBarService(barService: any): void {
this.barService = barService;
}
getBarService(): any {
return this.barService;
}
}
Run Code Online (Sandbox Code Playgroud)
我更新了此解决方案以使用Angular> 4.使用Injector类,您可以将服务注入另一个服务
import { Injector } from '@angular/core';
import { TempService } from './tmp';
@Injectable()
export class Temp2Service {
private tempService: any;
constructor (private injector: Injector) { }
public funcA() {
this.tempService = this.injector.get(TempService);
this.tempService.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个循环依赖,不幸的是,这是一个基本的计算机科学问题或信息问题,这是 Angular 无法解决的问题。尝试做这样的事情:
export class ServiceA{
constructor(private b: ServiceB){
b.setA(this);
}
}
export class ServiceB {
private a: ServiceA
constructor(){
}
setA(a){
this.a = a;
}
}
Run Code Online (Sandbox Code Playgroud)
这可能是最好的方法。
| 归档时间: |
|
| 查看次数: |
46240 次 |
| 最近记录: |