Array is undefined when trying to access it [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Array is undefined when trying to access it [duplicate]



This question already has an answer here:



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






This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





Replace then(this.gotDevices)by then(this.gotDevices.bind(this)) or by then(i => this.gotDevices(i))
– JB Nizet
Aug 12 at 10:17



then(this.gotDevices)


then(this.gotDevices.bind(this))


then(i => this.gotDevices(i))





@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 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 at 10:23





1 Answer
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);




Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

React Native Navigation and navigating to another Screen problem