3

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

我有 AuthService,在这里我处理身份验证结果并发出事件。

if (auth) { this.eAuth.emit(true) } else { this.eAuth.emit(false) }

我可以订阅 AuthComponent

_authService.eAuth.subscribe( (isAuth) => this.handleAuthResult(isAuth) )

它工作完美。但是 AggregateService 也需要知道这一点并将这些信息广播给 UserService、LoadDataService 等。

怎么做?

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

4

1 回答 1

6

如果将 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

于 2016-01-22T18:53:32.457 回答