Hey everyone, I'm encountering a small issue. I am attempting to retrieve some images from Flickr using their API, but for an unknown reason, the list is not populating at the desired time. Below is my code for better clarification.
This is the code snippet:
Component:
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);
}
}
}
Service:
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);
}
}
Output:
[ngOnInit 2]: 0
[ngOnInit 1]: 20
It's clear from the component code that my Interval function is never executed. It seems like the array doesn't have enough time to initialize itself. Why isn't it working as expected? What steps can I take to rectify this issue?
Please note that this question is unique since the problem persists even with the interval not functioning correctly either way.