简体   繁体   English

Array.push在ionic 4 Angular中不是函数问题

[英]Array.push is not a function problem in ionic 4 Angular

I am working with angular services called device service 我正在使用称为设备服务的角度服务

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');
        })
      }
    })
  }
}

I am injecting this service to a page and then calling its addDevice function with proper arguments which all works fine but at run time when trying to add a device it works for the first time and the first device gets added, the next time when it hits if conditions which check if an array exists and try appending to that by pushing another object it receives a run time error. 我正在将该服务注入到页面中,然后使用适当的参数调用其addDevice函数,这些参数都可以正常工作,但是在尝试添加设备时在运行时首次运行且添加了第一个设备,下次运行时如果条件检查数组是否存在,并尝试通过推入另一个对象来追加该数组,则它将收到运行时错误。

ERROR Error: Uncaught (in promise): TypeError: _this.devices.push is not a function 错误错误:未捕获(承诺):TypeError:_this.devices.push不是函数

I'm totally stuck at this moment IDE shows no error neither compiler. 我现在完全陷入困境,IDE都没有显示任何错误,编译器也没有。

You're getting this error because res is not array. 您收到此错误,因为res不是数组。 According to your comment, res an object with an array property called devices in it. 根据您的评论, res对象具有一个数组属性,该数组属性称为devices

Change it to: 更改为:

this.devices = res.devices 

You can add the devicesInterface interface to the callback parameter to avoid these kind of errors 您可以将devicesInterface接口添加到回调参数,以避免此类错误

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM