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:
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.