0

This might be a tricky question and i'm hoping to provide enough information to solve this since I'm already trying for hours.

I'm pretty sure that I have somehow instantiated two services since changes initiated from one components, didn't affect the other.

Below is the module structure.

SharedModule //reuseable cmps and so on..

AppModule({
  imports:[SharedModule, PageModule]
})

PageModule({
  imports:[SharedModule,CalendarModule]
})

CalendarModule({
  imports:[SharedModule],
  declarations:[CaldendarMonthCmp, CalendarCmp, CalendarDayCmp]
  providers:[CalendarService]
})

The CalendarService has an initialise method that passes the initial data.

calendarDays$: BehaviorSubject<sbCal.SbCalendarDay[]> = new BehaviorSubject([]);

intializeDays(day: sbCal.SbCalendarDay) {
  let newDays = [...data] // do some calculations, array not empty
  this.calendarDays$.next(newDays);
}

CaldendarMonthCmp displays a calendar in month grid and when I click any day, it initializes and passes on a newDays arrays and opens the CalendarDayCmp in a new page.

CalendarDayCmp subscribes to calendarDays$ but only gets an empty array and not the newDays.

My suspicion for two service instances hardened when I changed to code to

calendarDays$: BehaviorSubject<sbCal.SbCalendarDay[]>;
intializeDays(day: sbCal.SbCalendarDay) {
  let newDays = [...data] // do some calculations
  this.calendarDays$ = new BehaviorSubject(newDays);
}

instantiating the subject only if initialize has been called. In this case opening the CalendarDayCmp throws and can't subscribe to undefined error.

I've read through angular ngModule description and as far as I understand, instantiating more services only happens if I provide the Service to other modules?

Thanks for any help!

Han Che
  • 8,239
  • 19
  • 70
  • 116
  • It is also possible to instantiate additional instances in the components itself @Component({providers: [...]}) are you by chance creating an instance in one of your components? – LLai Aug 15 '17 at 16:14
  • no, i'm only injecting there. The strange part is that in an older project its works... – Han Che Aug 15 '17 at 16:20
  • if you add a console.log to initializeDays do you get multiple logs? confirming that there are multiple instances – LLai Aug 15 '17 at 16:53
  • Can also post your code of the component? One thing to remember is to unsubscribe calendarDays$ on destroying component If you don't want to see any thing weird. The last block of code throw an error because you tried to subscribe to the Subject before it was initialize. BehaviorSubject will emit a last value immediately after you subscribe to, so I suspect that the first data you receive is empty array but the second time should be correct. – Sasuke91 Aug 16 '17 at 01:26

0 Answers0