[英]Array.push is not a function problem in ionic 4 Angular
我正在使用稱為設備服務的角度服務
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
const TOTAL_DEVICES = "TOTAL_DEVICES";
interface deviceInterface {
ssid : String,
name : String
}
interface devicesInterface {
devices : Array<deviceInterface>
}
@Injectable({
providedIn: 'root'
})
export class DeviceService implements devicesInterface {
devices : Array<deviceInterface>;
constructor(private storage : Storage) { }
addDevice(ssid : String, name : String){
this.storage.get(TOTAL_DEVICES).then(res => {
if (res) {
this.devices = res;
console.log(this.devices);
this.devices.push({ssid : ssid, name : name})
}else{
let devices_obj : devicesInterface = { devices : [{ssid : ssid, name : name}] }
this.storage.set(TOTAL_DEVICES,devices_obj).then(res => {
console.log('device added');
})
}
})
}
}
我正在將該服務注入到頁面中,然后使用適當的參數調用其addDevice函數,這些參數都可以正常工作,但是在嘗試添加設備時在運行時首次運行且添加了第一個設備,下次運行時如果條件檢查數組是否存在,並嘗試通過推入另一個對象來追加該數組,則它將收到運行時錯誤。
錯誤錯誤:未捕獲(承諾):TypeError:_this.devices.push不是函數
我現在完全陷入困境,IDE都沒有顯示任何錯誤,編譯器也沒有。
您收到此錯誤,因為res
不是數組。 根據您的評論, res
對象具有一個數組屬性,該數組屬性稱為devices
。
更改為:
this.devices = res.devices
您可以將devicesInterface
接口添加到回調參數,以避免此類錯誤
this.storage.get(TOTAL_DEVICES).then((res: devicesInterface) => { ... })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.