【问题标题】:Data returned as undefined in ngOnInit() but not in function在 ngOnInit() 中返回未定义但在函数中未定义的数据
【发布时间】:2020-04-09 03:18:06
【问题描述】:

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

【问题讨论】:

    标签: angular typescript angular9


    【解决方案1】:

    那是因为getAnimals 是异步的。这就是console.log(this.animalsFur); 返回未定义的原因,因为调用控制台语句时getAnimals 尚未完成运行。如果您想获得更多关于它的上下文,您应该阅读更多关于 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...');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-10
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      相关资源
      最近更新 更多