0

I have a service class in typescript, in the class i have declared a public array of strings, but when I trying push into the array it throws the undefined exception. What could I be doing wrong here?

Cannot read property 'audioInput' of undefined

The source code of the class is :

export class AudioService {
    public audioInput:Array<String>=[];
    _navigator=<any> navigator;
    constructor(){
    }
    getDevices(){
        this._navigator.mediaDevices.enumerateDevices().then(this.gotDevices)
    }
    gotDevices(deviceInfos) : any {
      for (let i = 0; i !== deviceInfos.length; ++i) {
        const deviceInfo = deviceInfos[i];
        let value = deviceInfo.deviceId;
        if (deviceInfo.kind === 'audioinput') {
          this.audioInput.push(deviceInfo.label);
        }
      }
    }
}
Ahsan Imtiaz
  • 295
  • 1
  • 4
  • 16
  • 4
    Replace `then(this.gotDevices)`by `then(this.gotDevices.bind(this))` or by `then(i => this.gotDevices(i)) ` – JB Nizet Aug 12 '18 at 10:17
  • @JBNizet How stupid of me, yes that is what I was missing. Can you post this as an answer so I can mark it correct. Thanks – Ahsan Imtiaz Aug 12 '18 at 10:22
  • This question is being asked every other day. As you see, I already flagged it as a duplicate. You can just delete it. – JB Nizet Aug 12 '18 at 10:23

1 Answers1

-1

If you are accessing 'this' inside cordova. it refers to window object. you need to define let me = this;

export class AudioService {
    public audioInput:Array<String>=[];
    _navigator=<any> navigator;
    constructor(){
    }
    getDevices(){
        this._navigator.mediaDevices.enumerateDevices().then(this.gotDevices)
    }
    gotDevices(deviceInfos) : any {
      let me = this.
      for (let i = 0; i !== deviceInfos.length; ++i) {
        const deviceInfo = deviceInfos[i];
        let value = deviceInfo.deviceId;
        if (deviceInfo.kind === 'audioinput') {
          me.audioInput.push(deviceInfo.label);
        }
      }
    }
}
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27