两个服务如何以双向方式相互通信?
How can two services communicate with each other in a bi-directional way?
一种方式是通过事件,另一种方式是通过调用方法。我试图在我的应用程序中实现聚合模式。
我有 AuthService,在这里我处理身份验证结果并发出事件。
if (auth) { this.eAuth.emit(true) } else { this.eAuth.emit(false) }
我可以订阅 AuthComponent
_authService.eAuth.subscribe( (isAuth) => this.handleAuthResult(isAuth) )
而且效果很好。但 AggregateService 也需要知道这一点,并将这些信息广播给 UserService、LoadDataService 等。
怎么做?
更新:我的 AggregateService 没有组件,我已经将 AuthService 注入其中。
如果 ServiceA 被注入到 ServiceB 中,ServiceB 可以调用 ServiceA 上的方法(因此 ServiceB → ServiceA 通信)并且它可以 subscribe()
到 ServiceA 可能公开的任何 Obervable(因此 ServiceA → 到 ServiceB 通信)。
缺少的是 ServiceA 直接调用 ServiceB 上的方法的能力。通常不推荐这样做,因为它会在服务之间创建耦合。 ServiceA 应该在 ServiceB 可以 subscribe()
到的 Observable 上使用 next()
发出事件,然后 ServiceB 可以在其自身上调用适当的方法。
但是,如果您确实需要这样做,可以采用以下一种方法:让 ServiceB 在 ServiceA 上调用某种 registerService(this)
方法。参数的类型应该是接口而不是具体类型,以限制耦合。然后 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() { ... }
}
一种方式是通过事件,另一种方式是通过调用方法。我试图在我的应用程序中实现聚合模式。
我有 AuthService,在这里我处理身份验证结果并发出事件。
if (auth) { this.eAuth.emit(true) } else { this.eAuth.emit(false) }
我可以订阅 AuthComponent
_authService.eAuth.subscribe( (isAuth) => this.handleAuthResult(isAuth) )
而且效果很好。但 AggregateService 也需要知道这一点,并将这些信息广播给 UserService、LoadDataService 等。
怎么做?
更新:我的 AggregateService 没有组件,我已经将 AuthService 注入其中。
如果 ServiceA 被注入到 ServiceB 中,ServiceB 可以调用 ServiceA 上的方法(因此 ServiceB → ServiceA 通信)并且它可以 subscribe()
到 ServiceA 可能公开的任何 Obervable(因此 ServiceA → 到 ServiceB 通信)。
缺少的是 ServiceA 直接调用 ServiceB 上的方法的能力。通常不推荐这样做,因为它会在服务之间创建耦合。 ServiceA 应该在 ServiceB 可以 subscribe()
到的 Observable 上使用 next()
发出事件,然后 ServiceB 可以在其自身上调用适当的方法。
但是,如果您确实需要这样做,可以采用以下一种方法:让 ServiceB 在 ServiceA 上调用某种 registerService(this)
方法。参数的类型应该是接口而不是具体类型,以限制耦合。然后 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() { ... }
}