gpt4 book ai didi

angular - 服务相依

转载 作者:太空狗 更新时间:2023-10-29 16:46:25 25 4
gpt4 key购买 nike

在我的 Angular 2 应用程序中,我有两个相互依赖的服务(服务 A 从服务 B 调用方法,反之亦然)。

相关代码如下:

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 { (...) }

服务 1:

import {Injectable} from 'angular2/core';
import {Temp2Service} from './tmp2';

@Injectable()
export class TempService {
constructor (private _sessionService: Temp2Service) {}
}

服务 2:

import {Injectable} from 'angular2/core';
import {TempService} from './tmp';

@Injectable()
export class Temp2Service {
constructor (private _sessionService: TempService) {}
}

运行该应用程序会导致以下错误:

EXCEPTION: Cannot resolve all parameters for 'Temp2Service'(undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Temp2Service' is decorated with Injectable

在其中一项服务中评论构造函数时,应用程序运行良好。所以我的猜测是这两个服务的“交叉引用”导致了问题。

你知道这里出了什么问题吗?还是我的方法已经错了?

最佳答案

这就是所谓的循环依赖。这不是 Angular2 本身的问题。我知道的任何语言都不允许这样做。

您需要重构代码以消除这种循环依赖。您可能需要将其中一项服务分解为新服务。

如果你遵循单一责任原则,你会发现你不会陷入循环依赖陷阱。

关于angular - 服务相依,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com