Refactored CityComponent.

This commit is contained in:
Adriano Markovic
2020-04-05 13:14:56 +02:00
parent 649a3a836b
commit e01aaef9ca
2 changed files with 57 additions and 172 deletions
@@ -36,39 +36,37 @@ export class CityForecastService {
) { }
/**
* Fetches the weather forecast for a particular city summarizes the retrieved
* data into daily chunks. If specified, it also calculates the night, morning,
* noon and evening chunks for a particular day.
* Fetches all the available weather forecast data for a particular city
* and summarizes the retrieved data into daily chunks.
*
* @param city The city to retrieve the weather forecast from.
* @param date The start date.
* @param fetchDayTime Determines if also the time of a day
* chunks should be calculated.
* @return A object which includes an array of max. 2 BehaviorSubjects that contain
* the fetched results and an other BehaviorSubject which contains the error
* response if the http call fails.
* @return A object which includes the raw forecast data, an array of maximal 2
* BehaviorSubjects that contain the daily data and a BehaviorSubject
* which contains the error response if the http call fails.
*/
fetchDayForcasts(city: City, date: Date, fetchDayTime: boolean = false): {
fetchCompleteForecast(city: City, date: Date): {
forecast: BehaviorSubject<WeatherForecast>,
subjects: Array<BehaviorSubject<WeatherConditionSummary[]>>;
error: BehaviorSubject<any>
} {
const forecast = new BehaviorSubject<WeatherForecast>(null);
const subjects = new Array<BehaviorSubject<WeatherConditionSummary[]>>();
for (let i = 0; i < (fetchDayTime ? 1 : 2); i++) {
for (let i = 0; i < 2; i++) {
subjects.push(new BehaviorSubject<WeatherConditionSummary[]>(null));
}
const error = new BehaviorSubject<any>(null);
const subscription = this.apiClientService.getCityForecast(city.id).subscribe(
(forecast: WeatherForecast) => {
forecast.conditions.sort((a, b) => a.time - b.time);
subjects[0].next(this.computeDailySummary(forecast, city, date));
if (fetchDayTime) {
subjects[1].next(this.computeTimeOfDaySummary(subjects[0].value, false));
}
subscription.unsubscribe();
(f: WeatherForecast) => {
forecast.next(f);
f.conditions.sort((a, b) => a.time - b.time);
subjects[0].next(this.computeDailySummary(f, city, date));
subjects[1].next(this.computeTimeOfDaySummary(subjects[0].value, false));
subscription.unsubscribe();
},
(err: any) => error.next(err)
);
return { subjects, error };
return { forecast, subjects, error };
}
/**
@@ -1,10 +1,11 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Subscription, BehaviorSubject } from 'rxjs';
import { ResourceService } from '../services';
import { DefaultService, City, Geometry, WeatherCondition, WeatherForecast, WeatherVideo, WeatherStation } from '../api';
import { LocalTimePipe, LocalDatePipe } from '../pipes';
import { ResourceService, CityForecastService, WeatherConditionSummary } from '../services';
import { DefaultService, City, Geometry, WeatherCondition,
WeatherForecast, WeatherVideo, WeatherStation } from '../api';
@Component({
selector: 'app-city',
@@ -26,163 +27,49 @@ export class CityComponent implements OnInit, OnDestroy {
constructor(
public res: ResourceService,
private apiClientService: DefaultService,
private localTime: LocalTimePipe, private localDate: LocalDatePipe,
private router: Router, private route: ActivatedRoute) { }
private cityForecastService: CityForecastService,
private route: ActivatedRoute
) { }
ngOnInit(): void {
this.forecast.subscribe((forecast) => {
if (forecast == null) {
this.dayForecasts.next(null);
this.daytimeForecasts.next(null);
} else {
this.recomputeSummaries(forecast);
ngOnInit(): void {
this.routeSubscription = this.route.params.subscribe((res) => {
this.date = new Date();
this.city = this.route.snapshot.data['city'];
this.boundary.next(null);
this.condition.next(null);
this.forecast.next(null);
this.videos.next(null);
this.station.next(null);
const cityId = this.city.id;
this.apiClientService.getCityBoundary(cityId).subscribe((boundary) => {
if (this.city.id === cityId) {
this.boundary.next(boundary);
}
});
this.routeSubscription = this.route.params.subscribe((res) => {
this.date = new Date();
this.city = this.route.snapshot.data['city'];
this.boundary.next(null);
this.condition.next(null);
this.forecast.next(null);
this.videos.next(null);
this.station.next(null);
const cityId = this.city.id;
this.apiClientService.getCityBoundary(cityId).subscribe((boundary) => {
if (this.city.id === cityId) {
this.boundary.next(boundary);
}
});
this.apiClientService.getCityCondition(cityId).subscribe((condition) => {
if (this.city.id === cityId) {
this.condition.next(condition);
}
});
this.apiClientService.getCityForecast(cityId).subscribe((forecast) => {
if (this.city.id === cityId) {
// ensure that conditions are sorted
forecast.conditions.sort((a, b) => a.time - b.time);
this.forecast.next(forecast);
}
});
this.apiClientService.getLatestCityVideos(cityId).subscribe((videos) => {
if (this.city.id === cityId) {
this.videos.next(videos);
}
});
this.apiClientService.getCityStation(cityId).subscribe((station)=> {
if (this.city.id === cityId) {
this.station.next(station);
}
});
});
}
ngOnDestroy(): void {
this.routeSubscription.unsubscribe();
}
private recomputeSummaries(forecast: WeatherForecast) {
const today = this.localDate.transform(this.date, this.city.timezone);
// compute daily forecasts
const day = new Array<WeatherConditionSummary>();
forecast.conditions.forEach((c) => {
const start = this.localDate.transform(c.time, this.city.timezone);
const end = this.localDate.transform(this.endTime(c), this.city.timezone);
if (day.length === 0 || day[day.length - 1].title !== start) {
day.push({ start: this.dayStart(c.time), title: start,
subtitle: this.res.strings('city_forecast_full_day'), conditions: [] });
}
day[day.length - 1].conditions.push(c);
if (start !== end) {
day.push({ start: this.dayStart(this.endTime(c)), title: end,
subtitle: this.res.strings('city_forecast_full_day'), conditions: [] });
day[day.length - 1].conditions.push(c);
this.apiClientService.getCityCondition(cityId).subscribe((condition) => {
if (this.city.id === cityId) {
this.condition.next(condition);
}
});
day.forEach((value, index) => {
if (value.title === today) {
value.title = this.res.strings('label_today');
if (index > 0) {
day[index - 1].title = this.res.strings('label_yesterday');
}
if (day.length > index + 1) {
day[index + 1].title = this.res.strings('label_tomorrow');
}
this.apiClientService.getLatestCityVideos(cityId).subscribe((videos) => {
if (this.city.id === cityId) {
this.videos.next(videos);
}
});
// compute time-of-day forecast
const times = new Array<WeatherConditionSummary>();
day.forEach((wcs) => {
const strings = [ 'city_forecast_daytime_night', 'city_forecast_daytime_morning',
'city_forecast_daytime_afternoon', 'city_forecast_daytime_evening' ];
const summaries = new Array<WeatherConditionSummary>();
const ranges = new Array<number>();
let time = wcs.start;
ranges.push(time);
strings.forEach((resource) => {
summaries.push({ start: time, title: wcs.title, subtitle: this.res.strings(resource), conditions: [] });
time = this.addHours(time, 6);
ranges.push(time);
});
wcs.conditions.forEach((con) => {
const start = this.startTime(con);
const end = this.endTime(con);
for (let i = 0; i < strings.length; i++) {
const from = ranges[i];
const to = ranges[i + 1];
if (! (end < from || start >= to)) {
summaries[i].conditions.push(con);
}
}
});
summaries.forEach(s => {
if (s.conditions.length > 0) {
times.push(s);
}
});
});
// remove days with very litte predictions at the end
// of the prediction period
for (let i = day.length - 1; i >= 0; i--) {
if (day[i].conditions.length >= 3) {
break;
this.apiClientService.getCityStation(cityId).subscribe((station) => {
if (this.city.id === cityId) {
this.station.next(station);
}
day.splice(i, 1);
}
this.dayForecasts.next(day);
this.daytimeForecasts.next(times);
}
addHours(time: number, hours: number) {
const date = new Date(time);
date.setHours(date.getHours() + hours);
return date.getTime();
}
startTime(c: WeatherCondition): number {
return c.time;
}
endTime(c: WeatherCondition): number {
return c.time + (c.duration * 60 * 60 * 1000) - 1;
}
dayStart(time: number): number {
const d = new Date(time);
const offsets = d.toLocaleTimeString('de', {timeZone: this.city.timezone}).split(':', 3);
d.setMilliseconds(0);
d.setHours(d.getHours() - +offsets[0], d.getMinutes() - +offsets[1], d.getSeconds() - +offsets[2]);
return d.getTime();
}
});
const { forecast, subjects, error } = this.cityForecastService
.fetchCompleteForecast(this.city, this.date);
this.forecast = forecast;
this.dayForecasts = subjects[0];
this.daytimeForecasts = subjects[1];
});
}
}
/* An interface to summarize weather conditions */
export interface WeatherConditionSummary {
start: number; // the start time of the condition
title: string; // the title
subtitle: string; // the subtitle
conditions: WeatherCondition[]; // the conditions to aggregate
ngOnDestroy(): void {
this.routeSubscription.unsubscribe();
}
}