Данные возвращаются как неопределенные в ngOnInit (), но не в функции - PullRequest
1 голос
/ 09 апреля 2020

Я возвращаю данные из 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...');
    });
  }

Console.log Я оставил в id тот, который возвращает undefined, если я ставлю один (например) после завершения переключения, или в операторе case правильные данные отображаются в консоли, а не в onInit

1 Ответ

2 голосов
/ 09 апреля 2020

Это потому, что 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...');
});
...