如果将 ServiceA 注入到 ServiceB 中,则 ServiceB 可以调用 ServiceA 上的方法(因此 ServiceB → ServiceA 通信),并且可以subscribe()
调用 ServiceA 可能暴露的任何 Obervable(因此 ServiceA → 到 ServiceB 通信)。
缺少的是 ServiceA 直接调用 ServiceB 上的方法的能力。通常不建议这样做,因为它会在服务之间产生耦合。ServiceA 应该在 ServiceB 可以使用next()
的 Observable 上发出事件subscribe()
,然后 ServiceB 可以在其自身上调用适当的方法。
registerService(this)
但是,如果你真的需要它来工作,这里有一种方法:让 ServiceB在 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
}
}
ServiceB 应该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