When initializing in the ngOnInit()
method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Unfortunately, using rxjs mapping operators like mergeMap, switchMap, concatMap, or exhaustMap is not feasible due to the separation of these methods and other required operations.
This is a simplified version of what I currently have:
public taskTypes: any; // variable awaiting initialization
public firstDataSource: any;
public secondDataSource: any;
// additional variables requiring initial setup
constructor(...) {
this.taskTypes = [];
this.firstDataSource = [];
this.secondDataSource = [];
// additional initializations
}
ngOnInit() {
this.getTaskTypes();
this.methodOne();
this.methodTwo()
}
public getTaskTypes(): void {
this.http.get("url").subscribe(
(res) => {
this.taskTypes = res.tasks;
// perform additional operations on response data
// set other variables
},
(err) => {}
);
// additional operations involving variables
}
public methodOne(): void {
if (this.taskTypes.length > 0) {
this.http.get("url/" + 1).subscribe(
(res) => {
this.firstDataSource = res.data;
},
(err) => {}
);
}
// additional operations involving variables
}
public methodTwo(): void {
if (this.taskTypes.length > 0) {
this.http.get("url/" + 2).subscribe(
(res) => {
this.secondDataSource = res.data;
},
(err) => {}
);
}
// additional operations involving variables
}
The issue arises because upon calling ngOnInit()
, all internal methods are executed simultaneously. This results in the condition this.taskTypes.length > 0
always being evaluated as false
since the variable taskTypes
has not been initialized by the time methodOne()
and methodTwo()
are invoked. As a result, firstDataSource
and secondDataSource
do not receive the expected values from the corresponding API calls. Therefore, there is a necessity for methodOne()
and methodTwo()
to be called sequentially after getTaskTypes()
.