简体   繁体   中英

Unexpected result due to injecting service into service Angular 6

I am using ngrx-store and Angular 6 in my project. Unfortunately, I can't reproduce my issue ob the stackblitz , but i will describe my problem. I have Service1 that is used in the component and also Service2 , which is used inside Service1 . Service1 have few default properties that i am assigning before contstructor in it. So in my component on ngOnInit i make:

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

After this in effects i make:

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

The problem is that at the debugger point if i look into this.service2 it has inside service1 , because i am injected it there via DI, but this.service2.service1.items is empty array. It seems like service1 creates new instance of itself inside service2 . I expect that there should be data that i passes earlier in ngOnInit ( someData ). As you can see in the stackbltiz link services are providedIn: 'root' .

What i am doing wrong?

Finally, I found what was the problem. My Service1 was located into a separate module. And into this module, I had providers: [Service1] . So the service was creating two times instead of one. So removing in from providers declaration solved the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM