Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface.

Here is the interface structure:

export interface Interface{
  interfaceClassType: string;
}

The method to retrieve JSON data is as follows:

getJSON(): Observable<Interface[]> {
    return this.http.get<Interface[]>(URL)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }

To implement this, I have created the following code:

arrayWithObjects: Interface[];
 class1Array: Class1[];
 class2Array: Class2[];

 processJSON(): void {
    this.configService.getJSON().subscribe(results => this.arrayWithObjects = results);
    this.arrayWithObjects.forEach (function (object) {
      switch (object.interfaceClassType) {
        case "first":
          this.class1Array.push(object as Class1);
          break;
        case "second":
          this.class2Array.push(object as Class2);
          break;
      }
    }.bind(this))
  }

Even though the above implementation seems correct, calling it triggers an error message:

ERROR TypeError: this.class1Array is undefined

Answer №1

Two important points need to be addressed in this scenario.

  1. this.arrayWithObjects is assigned asynchronously, so when you try to use forEach, it may not be assigned yet. To fix this issue, consider moving the forEach inside the subscription block.
processJSON(): void {
  this.configService.getJSON().subscribe(results => {
    this.arrayWithObjects = results;
    this.arrayWithObjects.forEach (
      ...
    );
}

For more information on handling asynchronous data, visit this resource.

  1. Instead of using conventional JS function, switch to arrow function notation to correctly reference class member variables with the this keyword. In a regular JS function, this refers to the function's scope rather than the class context.
processJSON(): void {
  this.configService.getJSON().subscribe(results => {
    this.arrayWithObjects = results;
    this.arrayWithObjects.forEach((object) => {       // <-- apply arrow function here
      switch (object.interfaceClassType) {
        case "first":
          this.class1Array.push(object as Class1);
          break;
        case "second":
          this.class2Array.push(object as Class2);
          break;
      }
    });               // <-- no need for `bind()` method
  });
}

Answer №2

When you utilize a standard function as a callback, it does not maintain the scope of this within it. However, employing an arrow function resolves this issue.

this.arrayWithObjects.forEach ((object) => {
      console.log(this.class1Array);
})

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

There is no universal best common type that can cover all return expressions

While implementing Collection2 in my angular2-meteor project, I noticed that the code snippets from the demo on GitHub always result in a warning message being displayed in the terminal: "No best common type exists among return expressions." Is there a ...

Display responsive input field based on selected option in ionic2 dropdown menu

When the user selects 'Other' from the dropdown menu using Ionic2 and Angular2, I want to provide them with an option to enter their profession. Here is a visual representation of the select box: Below is the code snippet for achieving this fun ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

I'm puzzled as to why I am unable to retrieve the values from this array or parse the JSON data

When I make a call to an API, I am expecting a JSON array as the response. Here is what I receive: Array ( [0] => {"msg_id":"0t5OxT1ZP9VcF45L2","_text":"I want to reserve","entities":{"intent":[{"confidence":1,"value":"make_reservation","type":"val ...

My npm init script is failing to work properly. What steps can I take to troubleshoot

I am encountering an issue while setting up a new node.js project and attempting to generate the package.json file. As a Windows user, I am utilizing Visual Studio Code terminal for my project setup. However, when I enter the command npm init, I am faced w ...

Obtain information from a PHP file using AngularJS 2

Can you guide me on how to post data and receive a response from a PHP page in AngularJS 2? I want to send data from auth.js file to session.php for storing the session value. Please show me how to do this using HTTP POST method. retu ...

Using AngularJS to filter JSON data

Greetings! I possess the following JSON data: $scope.Facilities= [ { Name: "-Select-", Value: 0, RegionNumber: 0 }, { Name: "Facility1", Value: 1, RegionNumber: 1 }, { Name: ...

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

What could be the reason my component is not displaying the ContentChild associated with a directive?

It appears that utilizing a directive to target a content child from another directive is the recommended approach (source). However, why isn't my component able to recognize the component marked with the directive? ./my.component.ts import { Comp ...

Learn how to use jQuery to load a text file containing arrays and then format them as

I'm attempting to load a .txt file containing multidimensional arrays using AJAX, and then sort through the data to display it on my website. However, I'm facing an issue where the data is only returning as plain text, even after trying to use JS ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

How to shuffle the elements of an array saved in a JSON file using discord.js

I've been working on a Discord bot as a way to learn more about Javascript. While creating a command that pulls random quotes from an array stored in a separate JSON file, I encountered an issue that has me stumped. var config = require("./settings.j ...

Leveraging getStaticProps in Next.js

I am currently embarking on my inaugural Nextjs project, focused on developing a basic blog utilizing the JSON placeholder API. Strangely, I am encountering an issue where the prop "posts" is being perceived as undefined. Can anyone provide assistance with ...

How to retrieve properties of the final item in an array using Vue.js

Struggling with Vue.js JavaScript implementation. This is the current code: <div id="app"> <h1>Items</h1> <div v-for="item in items"> <input v-model="item.val"> </div> <button @click="addItem"> Ne ...

Error: The post method in $setup is not defined in Vue Composition API

Dealing with a frustrating issue in my Vue application. One page is functioning perfectly fine, while the other is causing trouble by displaying this error: The first page loads a collection of wordpress posts (Blog.vue) without any issues, but the second ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

Replacing the previous observation

My events app features an all-events component that showcases all the events created. Upon loading the all-events component, the events are fetched from the database. Below is a snippet of the relevant code from the Typescript file of the all-events compo ...

Updating a JSON file with new object using node.js

Currently, I am attempting to insert a single object into an extensive JSON file. My approach involves parsing the entire file using FS and JSON.Parse, adding the new JSON object in memory, and then rewriting the file. While I am aware of FS's append ...

Best practices for utilizing forwardRef and next/dynamic in next.js version 13.4 with the "react-email-editor" component

I've been attempting to utilize the "react-email-editor" library in a Next.js project. My goal is to copy the email content generated within the editor to the clipboard. Since the library relies on browser interaction and the use of the "window" objec ...

The script ceases to function once the page is loaded from a JSON file

I'm facing an issue on my shopping website where the items and products are loaded from a JSON file. The problem is that once the page has loaded, the script fails to work properly. If the items take a little longer to load on the page, the script doe ...