我的应用代码片段有一个非常有趣的问题。
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));
}
}
当在构造函数中执行randomizeCategories()方法时,所有运行都很顺利,但是当我单击按钮时在changeCategories()方法中调用此方法时,在浏览器的控制台中抛出错误:
49行代码为:
const wordID = this.getRandomArray(1, allCategories[categoriesIDsArray[categoryKey]].subcategories[subcategoryID].words.length - 1, 1);
wordID,subcategoryID变量未定义。
你有任何想法解决这个问题吗?
提前感谢您的帮助。
答案 0 :(得分:0)
在这种情况下,您在解析observable之前调用该方法,因此数组为空且面临错误。
要解决这个问题,你应该等到数组填满,所以在html中尝试:
<button *ngIf="categories?.length">...</button>
这样<button>
中的部分在数据可用之前不会呈现或使用(因为我已经在* ngIf中)安全导航操作符。 ?。这种方式属性之后。?仅在类别为!= null时进行评估。