我从API返回数据,并放入了几个console.log()
语句进行调试。在ngOnInit()
中,console.log
正在打印undefined
,但在单独的函数中,console.log
返回正确的数据,理论上,在这两者之间不进行其他处理。
ngOnInit() {
this.loadAnimalList('fur');
console.log(this.animalsFur);
}
loadAnimalList(classification: string) {
this.animalService.getAnimals(classification).subscribe((animals: Animal[]) => {
switch (classification) {
case 'fur':
this.animalsFur = animals;
break;
case 'feather':
this.animalsFeather = animals;
break;
case 'scales':
this.animalsScales = animals;
break;
case 'other':
this.animalsOther = animals;
break;
default:
this.animalsFur = animals;
break;
}
}, error => {
this.alertify.error(error, 'Failed to Load Animals...');
});
}
我在id中留下的console.log是返回未定义的,如果我在切换完成后放一个(例如(,或者在case语句中,那么正确的数据会显示在控制台中,而不是显示在onInit 中
这是因为getAnimals
是异步的。这就是console.log(this.animalsFur);
返回undefined的原因,因为调用console语句时getAnimals
尚未完成运行。如果你想获得更多关于JavaScript事件循环的上下文,你应该阅读更多关于它的内容
另一方面,在subscribe
中调用console
语句将确保为animalsFur
属性分配来自响应的值,因为subscribe
中的代码块将仅在返回来自getAnimals()
的可观测值之后运行。
this.animalService.getAnimals(classification).subscribe((animals: Animal[]) => {
switch (classification) {
case 'fur':
this.animalsFur = animals;
break;
case 'feather':
this.animalsFeather = animals;
break;
case 'scales':
this.animalsScales = animals;
break;
case 'other':
this.animalsOther = animals;
break;
default:
this.animalsFur = animals;
break;
}
// the below should be defined
console.log(animals);
// this should be defined as long classification === 'fur', or if the switch statement hits default case
console.log(this.animalsFur);
}, error => {
this.alertify.error(error, 'Failed to Load Animals...');
});