两种服务如何以双向方式相互通信?

iva*_*esi 3 angular2-services angular

一种是通过事件,另一种是通过调用方法。我试图在我的应用程序中实现聚合模式。

我有AuthService,在这里我处理auth结果并发出事件。

if (auth) { this.eAuth.emit(true) } else { this.eAuth.emit(false) }
Run Code Online (Sandbox Code Playgroud)

我可以订阅AuthComponent

_authService.eAuth.subscribe( (isAuth) => this.handleAuthResult(isAuth) )
Run Code Online (Sandbox Code Playgroud)

而且效果很好。但是AggregateService也需要了解这一点,并将此信息广播到UserService,LoadDataService等。

怎么做?

upd:我的AggregateService没有组件,我已经向其中注入AuthService。

Mar*_*cok 6

如果将ServiceA注入ServiceB,则ServiceB可以调用ServiceA上的方法(因此,ServiceB→ServiceA通信),并且可以 subscribe()访问ServiceA可能公开的任何Obervable(因此,ServiceA→与ServiceB通信)。

缺少的是ServiceA在ServiceB上直接调用方法的能力。通常不建议这样做,因为这会在服务之间建立耦合。ServiceA应该使用next()ServiceB可以使用的Observable 发出事件subscribe(),然后ServiceB可以在其自身上调用适当的方法。

但是,如果确实需要此方法,可以采用以下一种方法:让ServiceB registerService(this)在ServiceA上调用某种方法。参数的类型应该是接口而不是具体类型,以限制耦合。然后,ServiceA将引用ServiceB,并且可以在其中调用方法。

interface SomeInterface {
  public methodOne();
  public methodTwo();
}
Run Code Online (Sandbox Code Playgroud)

import {SomeInterface} from './some-interface';
export class ServiceA {
    registerService(someService:SomeInterface) {
       someService.methodOne(this);
       // you'll probably want to store someService in this object
    }
}
Run Code Online (Sandbox Code Playgroud)

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() { ... }
}
Run Code Online (Sandbox Code Playgroud)

Plunker