服务相互依赖 [英] Services depending on each other

查看:293
本文介绍了服务相互依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Angular 2 app, I have two services that depend on each other (service A calling methods from service B and vice versa).

以下是相关代码:

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

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

Running the app leads to the following error:

例外:无法解析以下参数的所有参数: 'Temp2Service'(未定义).确保所有参数都是 用Inject修饰或具有有效的类型注释,并且 'Temp2Service'用Injectable装饰

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

在其中一项服务中注释构造函数时,该应用程序运行良好.因此,我的猜测是两个服务的交叉引用"导致了问题.

When commenting the constructor in one of the services, the app runs fine. So my guess is that the "cross-reference" of the two services is causing the problem.

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

Do you have an idea what is going wrong here? Or is my approach already wrong?

推荐答案

这称为循环依赖. Angular2本身不是问题.我所知道的任何语言都不允许使用.

This is a called circular dependency. It is not an issue with Angular2 itself. It is not allowed in any language I am aware of.

您将需要重构代码以删除此循环依赖项.您可能需要将其中一项服务分解为新服务.

You will need to refactor your code to remove this circular dependency. Likely you will need to breakup one of these services into new service.

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

If you follow the single responsibility principle you will find you won't get into circular dependency trap.

这篇关于服务相互依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆