Can you help me solve this strange issue?
I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>
. The issue is that when the child component is loading, the data is undefined and only fills up after ngAfterViewInit
. I have also attempted to retrieve the data within this method, but it remains undefined. I tried implementing an approach using ngOnChanges
, but it seems that the data received from the Parent Component is not ready while the Child Component is loading. I also attempted to use async instead of subscribe. How can I ensure that the data is available when the child component is loading?
The code for the Parent and Child Components is provided below:
Parent Component
<child-component
[courses]="courses|async"
>
</child-component>
courses: any;
this.service.listCourses().subscribe((course: Course) => {
this.courses = course;
});
Child Component
private courses: any;
@Input()
set data(data: any) {
this.courses.next(data);
}
myControl = new FormControl('');
ngAfterViewInit() {
// >>> THIS THROWS ERROR AS this.courses is undefined
this.myControl.setValidators([
Validators.required,
forbiddenNamesValidator(this.courses)
]);
}
I have also attempted to use *ngIf
in HTML, but since the this.courses
parameter is used in the methods, it doesn't make sense to check the data in HTML.
The issue could be related to the subscribe method. I have also attempted to use promise, but I'm uncertain if I implemented it correctly.