I have to call some methods synchronically in ngOnInit()
method, but all of them make some asynchronous calls to an API from the inside. Some variables are setted in the first method, and the second and the third methods need these variables to be already setted. I can't use rxjs mapping operators (mergeMap, switchMap, concatMap, exhaustMap) since the calls are made from separated methods that make other operations.
This is what I have:
public taskTypes: any; // variable to be setted in first method
public firstDataSource: any;
public secondDataSource: any;
// some other variables to be setted in first method
constructor(...) {
this.taskTypes = [];
this.firstDataSource = [];
this.secondDataSource = [];
// some other initializations
}
ngOnInit() {
this.getTaskTypes();
this.methodOne();
this.methodTwo()
}
public getTaskTypes(): void {
this.http.get("url").subscribe(
(res) => {
this.taskTypes = res.tasks;
// some other operations with response data
// and set other variables
},
(err) => {}
);
// some other operations with variables
}
public methodOne(): void {
if (this.taskTypes.length > 0) {
this.http.get("url/" + 1).subscribe(
(res) => {
this.firstDataSource = res.data;
},
(err) => {}
);
}
// some other operations with variables
}
public methodTwo(): void {
if (this.taskTypes.length > 0) {
this.http.get("url/" + 2).subscribe(
(res) => {
this.secondDataSource = res.data;
},
(err) => {}
);
}
// some other operations with variables
}
My problem is that with the call of ngOnInit()
, all inner methods are called at the same time and the result of the condition: this.taskTypes.length > 0
is always false
because the variable taskTypes
has not been setted by the time when methodOne()
and methodTwo()
are called, so firstDataSource
and secondDataSource
never get setted with the respective calls to the API. That's why I need methodOne()
and methodTwo()
to be called synchronously after getTaskTypes()
.