import { Component, OnInit, OnDestroy } from '@angular/core'; import { DataService } from './../../services/data.service'; import { Router } from '@angular/router'; import { IntervalObservable } from 'rxjs/observable/IntervalObservable'; import { Subscription } from 'rxjs/Subscription'; import { Flight } from './../../classes/flight.class'; import { User } from './../../classes/user.class'; @Component({ selector: 'app-flights', templateUrl: './flights.component.html', styleUrls: ['./flights.component.css'] }) export class FlightsComponent implements OnInit, OnDestroy { loading:boolean = true; error:boolean = false; public subscription:Subscription; flights:Array = new Array(); constructor(private router: Router, private data:DataService){} getFlightsData(): void { this.data.load().then(()=> { this.data .flights() .subscribe(response => { var status = response.status_code; if(status != 200) { this.loading = false; this.error = true; } else{ for(let i = 0; i < response.data.length; i++) { var temp:Flight = Flight.toFlight(response.data[i]); var flight:Flight = this.getFlightByID(temp.id); if(flight) { if(!flight.equals(temp)) { // push new one, delete old var index = this.flights.indexOf(flight); this.flights.splice(index, 1); this.flights.push(temp); } } else { this.flights.push(temp); } } this.flights.sort((a, b) => { return a.id < b.id ? 1 : -1; }); this.loading = false; } }); }); } getFlightByID(id:number): Flight { return this.flights.find((f) => {return f.id === id}); } ngOnInit(): void { this.getFlightsData(); this.subscription = IntervalObservable.create(5000).subscribe(() => { console.log("Reloading data..."); this.getFlightsData(); }); } ngOnDestroy(): void { this.subscription.unsubscribe(); } onClick(flight: Flight): void { this.router.navigate(['/flight', flight.id]); } }