是否可以同时在另一个服务中注入一个服务,反之亦然? [英] Is it possible to inject a service inside another service and vice versa at the same time?
问题描述
我在一个真实的项目中有一个真实的场景,我需要2个服务来访问彼此的属性和/或方法.我不是Angular专家,所以有可能吗?
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?
我尝试过,但失败了.这是我的尝试:
I have tried and it fails. Here's my attempt:
app.component.ts
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
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
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;
}
}
柱塞: http://plnkr.co/edit/PQ7Uw1WHpvzPRf6yyLFd?p=preview
仅将第二个服务注入第一个服务就可以,但是一旦我将第一个服务注入第二个服务,它就会失败并向控制台抛出错误.
Just injecting the second service into the first service works fine but as soon as I inject the first service into the second service it fails and throws errors to the console.
那怎么了?
有效的解决方案应将以下内容打印到控制台日志中:
A working solution should print the following to the console log:
abcxyz
xyzabc
提前谢谢!
推荐答案
AngularJS不允许注入循环依赖项.
AngularJS does not allow injection of circular dependencies.
AngularJS的作者之一MiškoHevery建议找到共同的元素:
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 |<----| |
| | +---+ +---------+
+---------+
有关更多信息,请参见 MiškoHevery 中的构造函数中的循环依赖性和依赖性注入.
For more information, see Circular Dependency in constructors and Dependency Injection by Miško Hevery.
这篇关于是否可以同时在另一个服务中注入一个服务,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!