Home > Software design >  In Angular how can I communicate that all instances of a component have finished loading?
In Angular how can I communicate that all instances of a component have finished loading?

Time:08-30

I am currently working on two components & a service. Essentially ComponentA communicates with the service to populate a map with the inputs of ComponentA. ComponentB uses the fully populated map to load its view.

These components are essentially independent not a (child/parent of the other) but do share the same dependency injection which is the service.

The difficulty I'm having is that the number of ComponentAs in a view varies depending on the data being displayed so I do not know the number beforehand.

Essentially I'm looking for the following behavior:

  1. When a page is loaded the service starts with a notReadyState for CompB.
  2. X instances of CompA initialize and populate the map inside the service.
  3. Once the X instances of CompA have loaded the service communicates that the map is ready to be used by CompB.

This might be weird/difficult to implement so I am also open to alternative suggestions. To how CompB can get a list of the CompA inputs.

CodePudding user response:

You can use ReplaySubject.

Implement it in your service. When data are retrieved emit the value. And suscribe to it inside your componentB.

CodePudding user response:

if your componentAs and your componentB are at time (has the same parent) you get the data in parent and pass as @Input() the data to each componentA.

I imagine some like in your parent

<componentA *ngFor="let item of list;let i=index" [data]="data[i]|async">
</componentA>
<componentB [data]="allData">
</componentB>

//It's only one idea:

allData:any[]=[]
data:Observable[]=list.map(x=>this.service.getData(x.id).pipe(
   tap(x=>allData=allData.concat(x))
))
  • Related