I am trying to update local Storage with a function called addDevice(), it checks if there is already some data in a key then it appends to that else just update the key.
export class DeviceService implements devicesInterface {
devices : Array<deviceInterface> = [];
constructor(private storage : Storage, private http : HttpClient) { }
addDevice(ssid : String, name : String){
console.log("add device called "+ssid +name)
return this.getDevices().then((res : devicesInterface) => {
console.log("res");
console.log(res)
if (res) {
this.devices = res.devices;
console.log(res);
this.devices.push({ ssid: ssid, name: name });
return this.storage.set(TOTAL_DEVICES, { devices: this.devices });
}
else {
console.log("not res");
let devices_obj = { devices: [{ ssid: ssid, name: name }] };
return this.storage.set(TOTAL_DEVICES, devices_obj);
}
})
}
getDevices(){
return this.storage.get(TOTAL_DEVICES)
}
}
And from the page, I'm calling an API which resolves in an array of type deviceInterface.
this.deviceService.getDevicesFromServer(this.authenticationService.getToken())
.subscribe((res : Array<deviceInterface>) =>{
if(res){
this.storage.remove("TOTAL_DEVICES")
this.devices = []
}
res.map(async device => {
await this.deviceService.addDevice(device.ssid, device.name).then(res=>{
console.log("device added..")
this.devices.push(device)
console.log(res)
})
});
})
addDevice function has to be called in the chain, so that when next time its called it gets the data and append it, if this function is called asynchronously then data will get over-written again and again.
I have searched a lot but didn't find any relevant solution that matches my problem, how do I chain the iteration on res object and call addDevice function after the last call is resolved.