Encountered a null value when executing methods for the second time in an Angular application

I am facing an intriguing issue with a fragment of my app's code.

CategoriesPageComponent:

export class CategoriesPageComponent implements OnInit {

  private categories: Array<Category> = [];
  public randomizedCategories: Array<Category> = [];

  constructor(private router: Router,
              private categoriesService: CategoriesService){


    this.categoriesService.getAllCategories().subscribe((categories) => {
      this.categories = categories;
      this.randomizedCategories = this.randomizeCategories(this.categories, 7);
    });
  }

  ngOnInit() {
  }

  private randomizeCategories(allCategories, numberOfCategories): Array<Category> {
    const categoryArray = [];
    const categoriesIDsArray = this.getRandomArray(1, allCategories.length - 1, numberOfCategories);

    for (var categoryKey in categoriesIDsArray) {

      const subcategoryID = this.getRandomArray(1, allCategories[categoriesIDsArray[categoryKey]].subcategories.length - 1, 1);

      console.log(subcategoryID);
      const wordID = this.getRandomArray(1, allCategories[categoriesIDsArray[categoryKey]].subcategories[subcategoryID].words.length - 1, 1);

      const word: Word[] = allCategories[categoriesIDsArray[categoryKey]].subcategories[subcategoryID].words[wordID];
      const subcategory: Subcategory[] = allCategories[categoriesIDsArray[categoryKey]].subcategories[subcategoryID];
      subcategory['words'] = word;

      const category: Category = allCategories[categoriesIDsArray[categoryKey]];
      category.subcategories = subcategory;

      categoryArray.push(category);
    }

    return categoryArray;
  }

  getRandomArray(min, max, numOfElements) {
    let A = [];
    while (max >= min) {
      A.push(max--);
    }

    A.sort(function () {
      return .5 - Math.random();
    });
    return (numOfElements === 1) ? A[0] : A.slice(0, numOfElements);
  }

  changeCategories(){
    console.log(this.randomizeCategories(this.categories, 7));
  }
}

Whenever the randomizeCategories() method is called in the constructor, everything runs smoothly. However, when I trigger this method in the changeCategories() function by clicking a button, an error is displayed in the browser's console:

Error Screenshot

The error occurs at line 49 of the code:

  const wordID = this.getRandomArray(1, allCategories[categoriesIDsArray[categoryKey]].subcategories[subcategoryID].words.length - 1, 1);

The variables wordID and subcategoryID are undefined.

Any suggestions on how to resolve this issue would be greatly appreciated.

Thank you in advance for your help.

Answer №1

When calling the method before the observable is resolved, you may encounter an error due to the array being empty.

To resolve this issue, it is important to wait until the array is filled. In your HTML code, you can use the following:

<button *ngIf="categories?.length">...</button>

This ensures that the content within the <button> tags is only displayed once the data is available. Another option is to use the safe-navigation operator (?.) as shown in the *ngIf statement, where the property after ?. is evaluated only when categories is not null.

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

Encountering errors when subscribing to a BehaviorSubject in Angular 8

I am currently working on a Single Page Application using Angular 8 where I am trying to pass data from a component to a service. In the service, I am subscribing to it using rxjs BehaviorSubject. However, when I compile the code using Angular CLI, I encou ...

Moving a custom folder to production on Vercel with Next.js

I am currently working on developing a project using the NextJS environment. In this project, I have some JSON files stored in a folder within my root directory, and I am reading the content of these files in my code. Everything works fine on my local mach ...

Pixijs is unable to load spritesheets correctly

I am currently facing an issue while trying to load a spritesheet in PixiJS following the instructions provided on Below is the code snippet I am using: PIXI.Loader.shared.add('sheet', require('../assets/spritesheet.json')).load(sprite ...

Enable automatic profile login for the Firebase application

Imagine a web application created using Vue and Firebase. The main query revolves around automatically logging into the app after page reload, particularly accessing the database post authorization. Following user authentication, crucial data such as email ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

Why isn't my Vue.js3 table being updated after using axios asynchronously?

After conducting my research, it appears that I have followed all the correct steps. However, I am unable to identify why my table is not updating. Initially, I create a new company and proceed to the overview, but nothing is being displayed. While checki ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

Error with Firebase authentication on a Next.js project using TypeScript

I recently started a personal project using Next.js, Typescript, and Firebase for authentication and database management. While working on a sign-in page with Google integration, I encountered an error labeled as auth/argument-error. According to the Fireb ...

What could be causing my icon to not update when I click on it? (ionic/vue/ts)

Hey there, I'm having trouble changing my icon on click and I can't figure out why. Here's the template I'm using: <button> <ion-icon class="marge-image" :icon="onChange ? heart : heartOutline" @click=&quo ...

Encountering a 400 error in Firebase Cloud Messaging due to missing the "to" parameter

I am currently experimenting with sending a downstream push notification from an Android client for practice purposes only. When using the following code: private void send() { String urlString = "https://fcm.googleapis.com/fcm/send"; JSONObject ...

Creating a Sign-up Form and User Authentication System with AngularJS and AngularFire Firebase

I'm in the process of developing a web application using AngularJS that utilizes AngularFire and Firebase. One successful feature I have implemented is the Facebook authentication feature with Firebase, allowing users to log in using their personal F ...

The ngModel feature is not functioning properly when trying to update in tag inputs

I am having trouble with two-way data binding using ngModel in tag-inputs. Can someone please assist me? Here is the link to my code on StackBlitz ...

How does Vue compare to Angular in terms of components?

Is there a simple way to render dynamic components in Angular similar to how it's done in Vue? In Vue, rendering a dynamic component is as easy as this: <component v-bind:is="'componentX'"></component> How can this be ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

The issue with calling a public method from an onchange event triggered by a custom Google Maps control in the Ionic framework has been encountered

Hello, fellow developers! I am relatively new to Ionic and web programming in general. Currently, I am working on a small app that involves integrating the Google Maps JS API. While I have successfully created and loaded the map, as well as added a custom ...

Tips on eliminating expansion upon button click in header within an Angular application

While utilizing Angular Materials, I encountered a challenge with the mat-expansion component. Every time I click on the buttons within the expansion panel, it closes due to the default behavior of mat-panel. Requirement - The panel should remain expanded ...

Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows: const formService = new FormService(); const [appointmentDate, setAppointmentDate] = us ...

Ways to extract X-Total-Count from json-server using Angular's http.get function

Currently, I am utilizing json-server on localhost:3000. The setup is running smoothly, and I can fetch data in Angular through http.get. My objective is to access the response header X-Total-Count within the Angular .subscribe method. However, I am unab ...

What is the best way to implement jQuery functions such as datepicker within an Angular Component file?

My Angular code snippet is below: index.html <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"&g ...

The correlation between a TypeScript class and an interface bearing an identical name

I have been struggling to find clear documentation or explanation for the unique relationship between a TypeScript class and an interface that share the same name. What is the significance of having an interface with the same name as a class? Why does a ...