gpt4 book ai didi

angular - 两个服务如何以双向方式相互通信?

转载 作者:太空狗 更新时间:2023-10-29 18:14:28 24 4
gpt4 key购买 nike

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

我有 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 注入(inject)其中。

最佳答案

如果 ServiceA 被注入(inject)到 ServiceB 中,ServiceB 可以调用 ServiceA 上的方法(因此 ServiceB → ServiceA 通信)并且它可以 subscribe() 到 ServiceA 可能公开的任何 Obervable(因此 ServiceA → 到 ServiceB 通信) ).

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

但是,如果您真的需要它来工作,这里有一种方法:让 ServiceB 在 ServiceA 上调用某种 registerService(this) 方法。参数的类型应该是接口(interface)而不是具体类型,以限制耦合。然后 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 应该实现该接口(interface)——即,实现 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

关于angular - 两个服务如何以双向方式相互通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com