【发布时间】:2019-07-17 16:21:06
【问题描述】:
我正在使用称为设备服务的角度服务
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 函数,这一切正常,但在运行时尝试添加设备时,它第一次工作,第一个设备被添加,下一次当它遇到检查数组是否存在的 if 条件并尝试通过推送另一个对象来附加到该数组时,它会收到运行时错误。
ERROR 错误:未捕获(承诺中):TypeError:_this.devices.push 不是函数
此时我完全陷入困境,IDE 编译器都没有显示错误。
【问题讨论】:
-
res这里可能不是数组:this.devices = res -
查看其他情况 TOTAL_DEVICES 键具有此对象 { devices : [{ssid : ssid, name : name}] } 在 if 情况下由 res 获取
-
控制台日志记录 res 返回此 { devices : [{ssid : ssid, name : name}] }
-
它是devicesInterface类型的json对象
标签: javascript angular typescript ionic-framework interface