0
votes

I have an Angular app with the following structure:

  • Main component which renders several subcomponents in a <router-outlet>.
  • Service which has a resource as Subject<Resource>() and resource.asObservable().
  • Several subcomponents which subscribe to the observable.

My main component fetches a resource from an API. The subcomponents are supposed to display a part of the resource each.

Main component fetches the resource in ngOnInit, after which it sets the resource in the service using service.resource.next(). The problem is that it does this before the subcomponents are loaded (apparently), because the callback function that i passed to the subscribe function in the subcomponents does not get called.

The subcomponents subscribe to the resource in the service in their constructor.

How do i ensure that the main component sets the resource at a time where the subcomponents are loaded and can receive the update from the observable? Is there a different function that i need to use apart from ngOnInit? Or is there a different way entirely?

Thanks.

1

1 Answers

1
votes

instead of Subject<Resource>() you want ReplaySubject<Resource>(1)

replay subject will replay the last N emissions to new subscribers, where N is the argument to the constructor, so in this case, just the last 1.