Reputation: 53
I have a child component, which is loaded inside a parent component, but child is conditional and restricted loading with *ngIf condition
<app-child *ngIf="showChild"><app-child>
I have a common service, where there is a subject I`m subscribing in multiple places, but when child component is loaded later with showChild=true, the subscription for countryList$ is not working, because listener is attached later, any alternate solution for this??
Please help...
public countryList$ = new Subject();
Here is how I subscribe my countryList$
this.Service.countryList$.subscribe({
next: (response: CountryList) => {
this.countryList = response;
}
});
Upvotes: 1
Views: 449
Reputation: 4585
You could replace Subject
with BehaviorSubject
. This way the last emitted value would always be cached and late subscribers will directly get the last emitted value. Please note: BehaviorSubject needs an initial value, which could be an empty array in your case.
The Service that provides the data:
export class DataService {
public countryList$ = new BehaviorSubject([]);
constructor() { }
}
ChildComponent TS:
export class ChildComponent implements OnInit {
public countryList: any[];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.countryList$.subscribe(countryList => {
this.countryList = countryList;
});
}
}
Upvotes: 3