I want to implement a logic where if there is no network connectivity then i am storing the data in frontend in local storage and whenever got connected to network then I want to do api call on the this array of data from local storage. And if call is success then remove this item from storage and continue the process until done.
I have tried many ways using promise.all and forkJoin. Can anybody suggest the proper way to do it.
CodePudding user response:
You can do it with a simple approach. Firstly, you have to check if there is a network connection then you have to decide whether you have to store data in local storage or make an http
call.
You can get the internet connection status via this navigator.onLine
So let me give you a sample approach. Let's say you have a function to save customer data. So you can have like this
addCustomer(customerObject: Customer){
if(navigator.onLine){
// make api call
this.http.post('www.api-server.com/api/v1/customers', customerObject);
localStorage.setItem('customers', JSON.stringify([]));
} else {
let localCustomersData = JSON.parse(localStorage.getItem('customers'));
localCustomersData.push(customerObject);
localStorage.setItem('customers',JSON.stringify(localCustomersData));
}
}
CodePudding user response:
you can use online and offline listeners to run your functions which does set the list.
when you want to add an item to list, you check if there is an active network connection. which is possible by looking at navigator.onLine
.
which is explained in fahad's answer. when back online, to process the offline list, you can use event listeners to go through list and process the item.
addEventListener('online', (event) => processOffilineList());
with this you can create a listener that's triggered when you're online and the function can find the list from local storage and process the list.