When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly if the request has completed, or only wait a few seconds for it to finish.
In order to achieve this, once the user successfully logs in, I trigger the request for the large dataset:
this.getDataService.getAsyncData(data.LinkToken); // Initiate request from data service
The retrieved data is then saved into local storage and made available for retrieval when the user lands on the corresponding route triggering that request through ngOnInit()
getAsyncData(linkToken){ // Background request loading while user navigates
this.httpC.get(this.baseUrl + "/AccountInfo/Data?linkToken=" + linkToken + "&deliveryTypeId=" + 0 + "&pickupLocationId=" + 0 + "&paymentTypeId=" + 0).map((res:Response) => res.json()).subscribe(res => {
this.asycCollection = res;
this.globalService.setData(this.asycCollection) // Store data in local storage
console.log(this.asycCollection);
})
}
Subsequently, this data can be retrieved as a promise request within the component once the route loads
// Set local storage with the data
setData(refillObject:any){
this.refillObj = refillObject;
window.localStorage.setItem("refillData", JSON.stringify(this.refillObj))
}
// Retrieve promise of the background async call
getData(){
let refillInformation:any = window.localStorage.getItem("refillData");
return new Promise<any>((resolve, reject) => resolve(refillInformation));
}
Now, the challenge is ensuring that the data is only retrieved after it has finished loading, without causing any issues. If the user quickly navigates to the page before the data has finished loading, it returns null and causes errors. However, if they return after the data has finished loading, everything works smoothly as intended.
So, how can I effectively wait and retrieve the data only once it has finished loading? Remember, this data was originally fetched as a background async request upon user login and is now being accessed from local storage rather than making a new request to the REST Service.
Component Code:
getAsyncRefills(success){
this.globalService.getData().then(data => { // The code below will throw errors if the page is loaded before the data request completes and stores in local storage.
this.orderData = JSON.parse(data);
this.currentDeliveryType = this.orderData.DeliveryTypes.find((item) =>
item.DeliveryTypeId == this.orderData.DeliveryTypeId);
this.currentPaymentArr = this.currentDeliveryType.PaymentTypes;
this.currentPickupLocations = this.currentDeliveryType.PickupLocations;
this.setOptions();
this.buildOrders();
})
}