[英]Issue with component initialization Angular
嘿,我有一個小問題。 我試圖從其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
如您在組件代碼中看到的,我的時間間隔從不執行。 看起來該數組沒有時間初始化自身。 為什么它不起作用? 我該怎么做才能使它工作?
這不會重復,因為問題是間隔無法正常工作。
您正在執行代碼,然后才能獲得響應。 您的間隔代碼需要在響應塊內移動-
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);
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.