Это потому, что getAnimals
является асинхронным. Вот почему console.log(this.animalsFur);
возвращает неопределенное значение, так как getAnimals
не завершил работу при вызове оператора консоли. Вы должны прочитать больше о циклах *1005* событий *1005*, если хотите получить больше информации об этом.
С другой стороны, вызов оператора console
в subscribe
будет гарантировать, что свойству 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...');
});