When attempting to access the array, it is not defined

I'm encountering an issue with my TypeScript service class. I've declared a public array of strings within the class, but when I attempt to push values into the array, an undefined exception is thrown. Can someone help me identify what I might be doing wrong?

Cannot read property 'audioInput' of undefined

Here's the code snippet for the class:

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

Answer №1

If you are working with 'this' in cordova, it actually refers to the window object. To avoid any confusion, it is recommended to define a variable like 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);
        }
      }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up Angular2 webpack to run behind a reverse proxy on a subpath

I am looking to configure angular2-webpack-starter behind an Apache reverse proxy with URLs starting with a fixed prefix like /angular2-webpack-starter/. I came across this setting: output: { publicPath:"angular2-webpack-starter", ... Is this the cor ...

Using *ngIf with local variables in Angular 2: How to prevent binding to only the first element of an array

Check out the code on Plunker: https://plnkr.co/edit/te67zdtkVkNCUzEtW5XO?p=preview. Look at app.ts for details. Scenario: In this setup, the parent component holds an array and displays one element from it. The ChildComponent is a list that shows all el ...

Using Angular, is it possible to dynamically incorporate controls into an existing template based on datatype conditions

Looking for a solution using Angular4: I currently have multiple if statements in my component's template, and anticipate adding more in the future. To streamline this process, I am interested in implementing a factory class that generates templates b ...

How to Connect to Printer in Ionic 2

Does anyone know if there is an option to implement printing/connecting a printer from Ionic 2? Is there a Cordova plugin available for printing? I found this plugin: Cordova Print plugin Any help/information on this would be greatly appreciated. Also, i ...

Nativescript CSS - Issue: the first parameter in require must be a string

When attempting to create platform-specific CSS for my app component, I encountered an error. While my android.css file is functioning properly, the common.css file is not working. Any insights as to why this may be happening? JS: Error: /app.component.co ...

What is the reason for the inability of `Array<Value>, Value` to properly retrieve the type of the array value?

I am encountering an issue with the type declaration below: function eachr<Subject extends Array<Value>, Value>( subject: Subject, callback: ( this: Subject, value: Value, key: number, subject: Subject ...

Tips for aligning the text horizontally in an input field with a neighboring element

Hello amazing community, I'm searching for a neat way to align the text of an element horizontally with that of an Angular Material input field. Here is the code I am using: <div style="display: flex"> <div>Greeting: </div> ...

What could be causing the issue where I am receiving the error message that says: "Unable to access properties of undefined (reading 'index')"?

Here is the code snippet from my template: <mat-tab-group mat-align-tabs="start" (selectedTabChange)="ngOnInit($event)"> This is the ngOnInit function: ngOnInit(evt: any) { this.api.getApi().subscribe( ({tool, beuty}) => ...

Angular 8 hybrid application fails to detect AngularJS components

I recently embarked on developing a hybrid application and took the following steps: Added Angular 8 dependencies Inserted polyfills.ts Removed the ng-app attribute from my root index.html Manually bootstrapped the AngularJs app This is how my Angular i ...

The Angular 8 click event operates like a JavaScript onload function

I have integrated my angular application into an iframe portlet. On the parent JSP page, there is a form with an invisible submit button. Clicking this button opens a popup window from an external application. I am attempting to trigger the click event o ...

Sign up for the category that failed to assign a worth

Currently, I have a service that includes a getter and setter: // Service import { Subject } from 'rxjs'; export class MyService { public currentUser: any = new Subject(); ... there is a function where I call setCurrent and assign value ...

Check the compatibility of Angular 9 using TypeScript alongside Mocha and JavaScript syntax

After transitioning to Angular 9 (Type Script) from Angular.js, we aim to stick with Mocha for writing tests while maintaining the JavaScript syntax instead of using TypeScript in Mocha. Is it viable to write JavaScript tests for Type Script code, specifi ...

Utilize Typescript to ensure uniformity in object structure across two choices

Looking to create a tab component that can display tabs either with icons or plain text. Instead of passing in the variant, I am considering using Typescript to verify if any of the icons have an attribute called iconName. If one icon has it, then all othe ...

Error encountered in Ionic3 Angular6: Template parsing issue - the pipe 'translate' is not located in pages that have been added to the stack

I encountered the error message "Template parse errors: The pipe 'translate' could not be found". This error only occurs when I use the translate pipe in pages other than RootPage. Specifically, it works fine on the home page for translating labe ...

Connecting data from a .ts file in one webpage to the HTML content of another webpage

I am currently working on implementing the binding concept in Angular. The code snippet below is from PageOne.ts: this.navCtrl.push("PageTwo",{ paramType: params, }) Here is a snippet from PageTwo.html: <span>{{paramType}}</span> ...

Tips for triggering a modal window with unconventional number lengths or patterns

I attempted to trigger a modal based on specific sets of numbers entered in a form field, following the guidance provided here. The solution works well for handling a single length. However, when it comes to opening a modal based on different lengths of d ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

What are the potential downsides of using ID to access HTML elements in React TypeScript?

During my previous job, I was advised against accessing HTML elements directly in React TypeScript using methods like getElementById. Currently, as I work on implementing Chart.js, I initially used a useRef hook for setting up the chart. However, it appear ...

Expanding ngFor in Angular 2

Is it possible to pass two arguments with ngFor? Here is an example that I would like to achieve: <mat-card *ngFor="let room of arr; let floor of floorArr"> <mat-card-content> <h3>Room Number: {{room}}</h3> <p>Floor ...

Issue 2339: Dealing with || and Union Types

I've encountered an interesting issue while working with TypeScript and JavaScript. I created a code snippet that runs perfectly in JavaScript but throws a syntax error in TypeScript. You can check it out in action at this TypeScript Sandbox. Essenti ...