[英]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.