服务调用另一个服务,实现问题

时间:2019-05-07 02:26:53

标签: angular

我认为自己做错了,因为我可能不完全知道自己在做什么->

我有一个只有5个服务的模块,我只希望在那个模块中。

  providers: [
    {provide: SYNCH_MAP_TOKEN, useFactory: SynchMapFactory },
    {provide: SYNCH_WAYPOINT_TOKEN, useFactory: SynchWaypointFactory },
    forwardRef(() => NavigationWaypointSyncherService),
    forwardRef(() => NavigationMapSyncherService),
    NavigationControllerService
]

前2个是工厂制造的,因为我要使用2个不同类型的同一服务的2个不同实例:

export const SYNCH_MAP_TOKEN = new InjectionToken<SynchronizatorService<SynchMapElement, SynchMapElementSubject>>('Token for SynchMap');
export const SYNCH_WAYPOINT_TOKEN = new InjectionToken<SynchronizatorService<SynchWaypointElement, SynchWaypointElementSubject>>('Token for SynchWaypoint');

export const SynchMapFactory = () => new SynchronizatorService<SynchMapElement, SynchMapElementSubject>();
export const SynchWaypointFactory = () => new SynchronizatorService<SynchWaypointElement, SynchWaypointElementSubject>();

另外2个是forwardRef,因为它们需要2个令牌无效的服务

  constructor(@Inject(SYNCH_WAYPOINT_TOKEN) synchService: SynchronizatorService<SynchWaypointElement, SynchWaypointElementSubject>,
              private navigationControllerService: NavigationControllerService) {

但是这两项服务能够获得我的第五项服务NavigationControllerService的引用。

现在,我还希望NavigationControllerService获得NavigationWaypointSyncherServiceNavigationMapSyncherService的引用

但是这次,如果我这样做

constructor(public waypointSyncherService: NavigationWaypointSyncherService)

我得到“无法解决NavigationControllerService的所有参数

我相信我无法从服务中的另一服务获取引用,但是它与带有forwardRef的2一起使用,而不与没有?

我正要在NavigationControllerService中调用“ init”函数,在该函数中存储其他2个服务的引用,但是该实现可以吗?

1 个答案:

答案 0 :(得分:0)

您的问题来自于NavigationControllerService和NavigationWaypointSyncherService,NavigationMapSyncherService服务之间的循环依赖关系。

我认为我不明白为什么您需要对这两个服务使用forwardRef,但实际上您的解决方案也是forwardRef。 这是一篇与您的案例有关的好文章,解释了forwardRef在循环依赖管理中的用法。

https://docs.nestjs.com/fundamentals/circular-dependency