由于将服务注入服务 Angular 6 而导致的意外结果

Unexpected result due to injecting service into service Angular 6

我在我的项目中使用 ngrx-store 和 Angular 6。不幸的是,我无法在 stackblitz 中重现我的问题,但我会描述我的问题。我有在组件中使用的 Service1 和在 Service1 中使用的 Service2Service1 我在其中的构造函数之前分配的默认属性很少。所以在我 ngOnInit 的组件中我做了:

ngOnInit() {
  this.service1.init(someData);
}

在此之后我制作的效果:

 @Effect({
    dispatch: false
  })
  addItem$ = this.actions$.pipe(
    ofType(fromReducers.AddItem),
    map((action: AddItem) => action.payload),
    tap(item=> *debugger* this.service2.addItemToService1(item))
  );

问题是,在 调试器 点,如果我查看 this.service2 它在 service1 里面,因为我是通过 DI 注入它的,但是 this.service2.service1.items 是空数组。似乎 service1service2 中创建了自己的新实例。我希望应该有我在 ngOnInit (someData) 中较早传递的数据。 正如您在 stackbltiz link 中看到的那样,服务是 providedIn: 'root'.

我做错了什么?

终于找到问题所在了。我的 Service1 位于一个单独的模块中。在这个模块中,我有 providers: [Service1]。所以该服务创建了两次而不是一次。所以从提供者声明中删除解决了问题