I have several functions in a form creation component that I need to be called at the same time. In fact, each of them are valid values that are allowed values of one of the dropdown form fields. For example, gender, countries, interests, that values come from the server. I subscribed to them in separate functions and now called them in the ngOninit. This works fine, but is there a better way to call multiple functions in parallel?
ngOnInit() {
this.gender();
this.countries();
this.interests();
}
gender() {
this.apiService.gender().subscribe((res: any) => {
this.gender = res;
}, error => {
console.log(error);
});
}
}
countries() {
this.apiService.countries().subscribe((res: any) => {
this.countries = res;
}, error => {
console.log(error);
});
}
interests() {
this.apiService.interests().subscribe((res: any) => {
this.countries = res;
}, error => {
console.log(error);
});
}
with forkjoin:
ngOnInit() {
forkjoin([this.getGender(), this.getCountries(), this.getInterests()]).subscribe();
}
getGender() {
return this.apiService.gender().pipe(tap(gender => (this.gender = gender)));
}
getCountries() {
return this.apiService.countries().pipe(tap(countries => (this.countries = countries)));
}
getInterests() {
return this.apiService.interests().pipe(tap(interests => (this.interests = interests)));
}