组件初始化Angular的问题

时间:2018-10-12 21:57:22

标签: javascript angular typescript

嘿,我有一个小问题。我试图从其api中提取一些Flickr图像,由于我不知道的原因,该列表在我希望的时间未填充。我将发布代码以更好地进行解释。

这是我的代码:

组件:

export class MainComponent implements OnInit {

  myArray: Item[] = [];
  randomItem: Item;

  constructor(private dataService: DataService) {
  }

  refresh(){
    console.log("[refresh()]:",this.myArray.length)
    var selected = Math.floor(Math.random() * this.myArray.length);
    this.randomItem = this.myArray[selected];
    this.myArray.splice(selected,1);

  }

  ngOnInit() {
    this.dataService.getImages().subscribe(res => {
      this.myArray = res.items;
      console.log("[ngOnInit]:" ,this.myArray.length)
    })

    console.log("[ngOnInit 2]:",this.myArray.length)
    if(this.myArray.length>0){
      var myInterval = setInterval(this.refresh(), 1000);
    }else{
      clearInterval(myInterval);
    }
    }

}

服务:

export class DataService {


 imagesUrl = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1';
  myArray:Item[]=[];
  randomItem:Item;

  constructor(private http: HttpClient) {
  }

  getImages(): Observable<Flickr>{
    return this.http.get<Flickr>(this.imagesUrl);
  }

}

输出:

  

[ngOnInit 2]:0

     

[ngOnInit 1]:20

正如您在组件代码中看到的那样,我的时间间隔从未执行。看起来该数组没有时间初始化自身。为什么它不起作用? 我该怎么做才能做到这一点?

之所以不能重复,是因为问题在于间隔无论如何都无法工作。

1 个答案:

答案 0 :(得分:2)

您正在执行代码,然后才能获得响应。您的间隔代码需要在响应块内移动-

private interval;

  refresh(){
    console.log("[refresh()]:",this.myArray.length)
    var selected = Math.floor(Math.random() * this.myArray.length);
    this.randomItem = this.myArray[selected];
    this.myArray.splice(selected,1);

    if(this.myArray.length == 0){
       clearInterval(this.interval);
    }
  }

    ngOnInit() {
        this.dataService.getImages().subscribe(res => {
          this.myArray = res.items;
          console.log("[ngOnInit]:" ,this.myArray.length)

           this.interval = setInterval(() => {
              this.refresh(); 
           }, 1000);

        })

    }
相关问题