数据在 ngOnInit() 中返回为未定义但在函数中没有

Data returned as undefined in ngOnInit() but not in function

我正在从 API 返回数据,并且我已经放入了几个 console.log() 语句用于调试。在 ngOnInit() 中,console.log 正在打印 undefined,但在单独的函数中 console.log returns 是正确的数据,理论上,没有进行其他处理介于两者之间。

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 中留下了 returns 未定义的那个,如果我在切换完成后放置一个(例如),或者在 case 语句中,那么正确的数据是显示在控制台中,只是不在 onInit

那是因为 getAnimals 是异步的。这就是 console.log(this.animalsFur); returns 未定义的原因,因为调用控制台语句时 getAnimals 尚未完成 运行ning。如果你想获得更多关于它的上下文,你应该阅读更多关于 JavaScript 的 event loops

另一方面,在 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...');
});