如果Service被注入到Service中,Service可以调用ServiceA上的方法(因此ServiceB→ServiceA通信)并且它可以subscribe()
到 ServiceA 可能公开的任何 Observable(因此 Service → 到 Service 通信)。
缺少的是 ServiceA 直接调用 ServiceB 上的方法的能力。通常不建议这样做,因为它会在服务之间产生耦合。 ServiceA 应该使用以下方式发出事件next()
ServiceB 可以在 Observable 上subscribe()
至此,服务可以调用自身适当的方法。
但是,如果您确实需要此功能,可以使用以下一种方法:让 ServiceB 调用某种registerService(this)
ServiceA 上的方法。参数的类型应该是接口而不是具体类型,以限制耦合。然后ServiceA将拥有对ServiceB的引用,并且可以调用其上的方法。
interface SomeInterface {
public methodOne();
public methodTwo();
}
import {SomeInterface} from './some-interface';
export class ServiceA {
registerService(someService:SomeInterface) {
someService.methodOne(this);
// you'll probably want to store someService in this object
}
}
服务B应该implement
该接口——即实现 ServiceA 可以调用的一组方法。
import {SomeInterface} from './some-interface';
export class ServiceB implements SomeInterface {
constructor(private _serviceA: ServiceA) {
_serviceA.registerService(this);
}
methodOne(who) {
console.log('hello from ServiceB.methodOne(), called by', who);
}
methodTwo() { ... }
}
Plunker http://plnkr.co/edit/YLiEg1GHUoo4CSz2A8WX?p=preview