Angular 返回的数据在ngOnInit()中未定义,但在函数中未定义
我从一个API返回数据,并放入了几个Angular 返回的数据在ngOnInit()中未定义,但在函数中未定义,angular,typescript,angular9,Angular,Typescript,Angular9,我从一个API返回数据,并放入了几个console.log()语句进行调试。在ngOnInit()中,console.log正在打印undefined,但在单独的函数中,console.log返回正确的数据,理论上,在这两个函数之间不会进行其他处理 ngOnInit() { this.loadAnimalList('fur'); console.log(this.animalsFur); } loadAnimalList(classification: string)
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中,这是因为
getanives
是异步的。这就是为什么console.log(this.animalsFur)
返回未定义,因为调用console语句时,getAnimals
尚未完成运行。如果您想了解更多关于JavaScript的内容,您应该阅读更多关于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...');
});
这是因为
getAnimals
是异步的。这就是为什么console.log(this.animalsFur)
返回未定义,因为调用console语句时,getAnimals
尚未完成运行。如果您想了解更多关于JavaScript的内容,您应该阅读更多关于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...');
});