循环的角度组件

时间:2019-07-18 13:49:19

标签: angular typescript

我正在尝试在组件中进行for循环,但未调用for循环。 不知道为什么它没有循环。我可以在html文件中循环播放,但不能在ts文件中循环播放

 export class examplecomponet implements OnInit {

   somelist:[];
   somevalue:any;

   ngOnInit() {
      for(let listvalue in  somelist){
        console.log("Checking list value",listvalue)// This is not called       
      }

}

      getSomeApi() { 
         this._auth.getApi().subscribe(data => {
            this.somevalue = data.text();      
            var v = JSON.parse(this.somevalue)
            this.somelist = v;      
         }
       );
   }
}
   checkLoop() { 
 console.log("Checking list value2",this. somelist.length)// this is 
      undefined
}

这是我的json响应

   {
 "Demo":{
 "Sample":"Test",
  },

 "Demo1":{
 "Sample1":"Test1",
  },

 }

2 个答案:

答案 0 :(得分:1)

改变逻辑,

   ngOnInit() {
      this.getSomeApi();
   }

   getSomeApi() { 
      this._auth.getApi().subscribe(data => {
         this.somevalue = data.text();    
         var s = JSON.parse(this.somevalue)
         this.somelist = v; //and where this "v" come from?
         for(let listvalue in  somelist){
            console.log("Checking list value",listvalue)// This is not called
      }

答案 1 :(得分:1)

这是因为在您调用循环时,未接收到getApi()函数的数据,因此未分配somelist值。尝试将其放在订阅旁边


logListValue(){
  for( let listvalue in  this.somelist){
  console.log("Checking list value",listvalue)
  }
}

//Put it in your subscribe

getSomeApi() { 
  this._auth.getApi().subscribe(data => {
    this.somevalue = data.text();
    var s = JSON.parse(this.somevalue)
    this.somelist = v;}
    //Add it here
    this.logListValue()
   );
}