I have a form component that inserts data into a database upon submission, and I need to update the displayed data in another component once it changes in the database. I attempted using ViewChild to invoke the necessary functions, but encountered issues with ViewChild being undefined after submission.
The DataComponent below is responsible for rendering the data on the HTML page:
export class DataComponent implements OnInit{
constructor(private dataService: DataService,private router:Router) {
this.getData();
}
ngOnInit(): void {
}
getData(){
this.dataService.getData().subscribe(
resp => this.data = resp,
error =>console.log(error)
);
}
detail(id: number){
this.router.navigate(['data/check' + id]);
}
}
And CheckComponent serves as the form component:
export class CheckComponent implements OnInit,AfterViewInit {
form: FormGroup;
data: any = [];
id: number;
@ViewChildren(DataComponent) dataComponent: DataComponent ;
constructor(
private formBuilder: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private dataService: DataService
) {
this.id = parseInt(this.route.snapshot.paramMap.get('id'));
this.Service.getReporte(this.id).subscribe(
(resp: any) => this.data = resp,
(error) => console.log(error)
);
}
}
ngOnInit(): void {
this.makeForm();
}
makeForm() {
this.form = this.formBuilder.group({
...
});
}
sendData() {
const data = {
...
};
this.dataService.createData(data).subscribe(
(resp) => console.log(resp),
(error) => console.log(error)
);
this.dataComponent.getData(); //undefined
this.router.navigate(['data']);
}
}
Is there an alternative method to call functions from another component instead of ViewChild? Have I implemented it incorrectly? I specifically need to access the getData() function from the DataComponent.