Я пытаюсь обновить локальное хранилище с помощью функции addDevice (), она проверяет, есть ли уже какие-либо данные в ключе, затем добавляет, что еще только обновляет ключ.
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)
}
}
И со страницы я вызываю API, который разрешается в массиве типа 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 должна вызываться в цепочке, чтобыкогда в следующий раз его вызывают, он получает данные и добавляет их, если эта функция вызывается асинхронно, тогда данные будут перезаписываться снова и снова.
Я много искал, но не нашел никакого подходящего решения, котороесоответствует моей проблеме, как мне связать итерацию в объекте res и вызвать функцию addDevice после того, как последний вызов разрешен.