1

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.

4
  • 1
    res is probably not an array here: this.devices = res Commented Feb 23, 2019 at 21:20
  • see the else case TOTAL_DEVICES key has this object { devices : [{ssid : ssid, name : name}] } fetched by res in if case Commented Feb 23, 2019 at 21:20
  • console logging res returns this { devices : [{ssid : ssid, name : name}] } Commented Feb 23, 2019 at 21:22
  • it json object of type devicesInterface Commented Feb 23, 2019 at 21:23

1 Answer 1

2

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) => { ... })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.