简体   繁体   中英

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.

ERROR Error: Uncaught (in promise): TypeError: _this.devices.push is not a function

I'm totally stuck at this moment IDE shows no error neither compiler.

You're getting this error because res is not array. According to your comment, res an object with an array property called devices in it.

Change it to:

this.devices = res.devices 

You can add the devicesInterface interface to the callback parameter to avoid these kind of errors

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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