【问题标题】:Array.push is not a function problem in ionic 4 AngularArray.push 不是 ionic 4 Angular 中的函数问题
【发布时间】: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


【解决方案1】:

您收到此错误是因为 res 不是数组。根据您的评论,res 是一个对象,其中包含一个名为 devices 的数组属性。

改成:

this.devices = res.devices 

您可以在回调参数中添加devicesInterface接口以避免此类错误

this.storage.get(TOTAL_DEVICES).then((res: devicesInterface) => { ... })

【讨论】:

    猜你喜欢
    • 2018-11-09
    • 2018-07-08
    • 2020-04-12
    • 2019-06-05
    • 2017-12-29
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多