I have an array of Objects from my service component that I want to read five random Objects from and display them one after another in the template with a delay. Once the last Object has been shown, it should start again from the beginning. I managed to achieve this without using Observables or RxJS library, but I believe there might be a more efficient way to do it. I'm curious about the Angular approach to accomplish this task.
Just to note, I am working with Angular 4.
service component:
getWeatherData(): Observable<IWeatherdata[]> {
return this.http.get("./assets/weatherdata.json")
.map(res => {
let data = res.json();
return data; // the data consists of 100 Objects
});
}
app component:
itemsWeatherData: IWeatherdata[] = [];
weatherObject: IWeatherdata[] = [];
ngOnInit() {
this.handleWeatherData();
}
handleWeatherData() {
return this._searchService.getWeatherData()
.subscribe (res => {
while (this.itemsWeatherData.length <= 4) {
let randomNum = this.randomNumber(0, 99);
let randomWeatherData = res[randomNum];
if (!this.itemsWeatherData.includes(randomWeatherData)) {
this.itemsWeatherData.push(randomWeatherData);
}
}
(function getWeatherObject(index = 0) {
this.weatherObject[0] = this.itemsWeatherData[index];
index < this.itemsWeatherData.length - 1
? setTimeout(getWeatherObject.bind(this), 20000, index += 1)
: setTimeout(getWeatherObject.bind(this), 20000, index = 0);
}).bind(this)();
})
}
in the template:
<div *ngFor="let data of weatherObject">
{{data}}
</div>
edit /*
The input is an array of Objects like so:
[Obj1, Obj2, Obj3, Obj4, Obj5]
The output is an array where the element is updated with a 20-second delay like this (displaying only one element at a time from the input array and repeating):
[Obj1] // delay 20sec
[Obj2] // delay 20sec
[Obj3] // delay 20sec
[Obj4] // delay 20sec
[Obj5] // delay 20sec
[Obj1] // delay 20sec
and so on ...
*/ edit
Although my current implementation works as expected, it seems a bit performance-heavy. I'm interested in understanding the Angular way of achieving this and would appreciate any guidance on concepts or operators I should explore for a more efficient solution.
Any insights on the advantages of using observables or other methods over my current approach would also be helpful.
Thank you from an Angular newbie!