首页 文章

无法获得在ngOnInit()中以角度动态生成的数组的长度

提问于
浏览
1

无法获得在ngOnInit()中以角度动态生成的数组的长度 .

@Component({
  selector: 'rise-our-champions',
  templateUrl: './our-champions.component.html',
  styleUrls: ['./our-champions.component.css']
})
export class OurChampionsComponent implements OnInit {

champs: any = [];

ngOnInit() {
    this.getChampions(0, 12, 'created_at', 'desc', this.campaignId); 
    console.log(this.champs);
    console.log(this.champs.length); //<================= This displays 0 where as my array populates with 4 values.
  }

  getChampions(offset: any, size: any, sort: any, order: any, id: any) {

    this._restApiService.getCampaignChampion(offset, size, sort, order, id).subscribe(
  data => {
    // this.champions = data['champions']
    data['champions'].forEach((champion: any) => {
      this.champs.push(champion);
    });

    if (data['champions'].length < 12) {
      this.showMore = false;
    } else {
      this.showMore = true;
    }
  },
  error => {
    if (error.status == 400) {
      this.router.navigate(['/error']);
    } else {
      this.errorMessage = <any>error,
        this.missionService.announceMissionToShowCustomAlert({
          requestType: FeatureType.showCustomAlert,
          title: 'Error',
          message: '<p>' + this.errorMessage + '</p>',
          redirectType: FeatureType.isError
        })
    }
  },
  () => {

  }
);

}

我在ngOnInit()生命周期钩子里调用函数,它显示以下输出,如何获取数组的长度?请参阅以下快照:
enter image description here

2 回答

  • 2

    由于 async 调用,您的 console.log() 在值存在之前打印 . 将 console.log() 放在 getChampions() 函数的订阅中,如下所示:

    getChampions(offset: any, size: any, sort: any, order: any, id: any) {
      this._restApiService.getCampaignChampion(offset, size, sort, order, id).subscribe(
        data => {
          // this.champions = data['champions']
          data['champions'].forEach((champion: any) => {
          this.champs.push(champion);
        });
    
        if (data['champions'].length < 12) {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
      },
      error => {
        if (error.status == 400) {
          this.router.navigate(['/error']);
        } else {
          this.errorMessage = <any>error,
            this.missionService.announceMissionToShowCustomAlert({
              requestType: FeatureType.showCustomAlert,
              title: 'Error',
              message: '<p>' + this.errorMessage + '</p>',
              redirectType: FeatureType.isError
            })
        }
      },
      () => {
         // THIS IS EXECUTED AFTER THE SUBSCRIBE COMPLETES
         console.log(this.champions);
      }
    }
    
  • 2

    您的this.getChampions函数会触发对服务器的异步api调用 . 所以你的console.log语句在你的this.champs设置之前执行

    因此,您需要在 ngOnInit 中返回服务调用和 .subscribe . 使用 .map hook在 this. getChampions`中执行数据操作 . 像这样,

    @Component({
          selector: 'rise-our-champions',
          templateUrl: './our-champions.component.html',
          styleUrls: ['./our-champions.component.css']
        })
        export class OurChampionsComponent implements OnInit {
    
          champs: any = [];
    
          ngOnInit() {
            this.getChampions(0, 12, 'created_at', 'desc', this.campaignId)
              .subscribe(() => {
                console.log(this.champs);
                console.log(this.champs.length);
              });
          }
    
          getChampions(offset: any, size: any, sort: any, order: any, id: any) {
    
        return this._restApiService.getCampaignChampion(offset, size, sort, order, id)
          .map(data => {
            // this.champions = data['champions']
            this.champs = data.champions;
            this.showMore = data.champions.length > 11;
          })
          .catch(error => {
            if (error.status == 400) {
              this.router.navigate(['/error']);
            } else {
              this.errorMessage = <any>error;
               this.missionService.announceMissionToShowCustomAlert({
                  requestType: FeatureType.showCustomAlert,
                  title: 'Error',
                  message: '<p>' + this.errorMessage + '</p>',
                  redirectType: FeatureType.isError
                })
            }
          });
    }
    
        }
    

相关问题