In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once the data is obtained and passed to the getCar() method, various data handling functions are immediately executed.
Upon building my project, it initiates a post Request followed by a get Request to the backend. Unfortunately, the get request is triggered before the post request is completed, causing the get request to return null data. Consequently, this leads to TypeErrors in the handling methods that expect valid data. Reloading the page resolves this issue as the proper data is then retrieved.
The objective now is to ensure that the data is fetched successfully on the initial request, requiring the getCar() method to wait until the post request is fully processed.
Here is the code snippet from my component where the services are invoked:
ngOnInit(): void {
this.postUrlData();
this.getCar();
}
postUrlData(){
this.route.queryParams.subscribe(params => {
this.urlData = {
vin : params['vin'],
dealerId: params['dealerid']
};
})
this.apiService.postURLData(this.urlData).subscribe();
}
getCar(){
this.apiService.getCertainCar().subscribe( data => {
this.carData = data;
console.log(data);
this.filltechDetails();
this.fillcarEquipment();
this.fillCarDetails();
});
}
Below are the api-services utilized:
@Injectable({
providedIn: 'root'
})
export class ApiServiceService {
constructor(private http: HttpClient) { }
getCertainCar(): Observable<any>{
return this.http.get(this.serverUrl+'/car')
}
postURLData(urlData:any):Observable<any>{
return this.http.post(this.serverUrl+"/urlData",urlData);
}
}