import { Injectable } from "@angular/core"; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { Observable, of } from "rxjs"; import { distinctUntilChanged, switchMap, catchError, map } from "rxjs/operators"; import { LatLng } from "leaflet"; import { environment } from '@environments/environment'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class WeatherService { constructor(private readonly http: HttpClient, private readonly authSvc: AuthService) { } getForcastAt(loc: LatLng): Observable { const _headers = new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8', }); const fcUrl = `/forecast/current.json?key=${environment.weatherKey}&q=${loc.lat},${loc.lng}&aqi=no&lang=${this.authSvc.locale}`; return this.http.get(fcUrl, { headers: _headers }); } atLocation(loc: Observable) { return loc.pipe( distinctUntilChanged(), switchMap( loc => { return this.getForcastAt(loc).pipe( map(data => { data['reqLatLon'] = loc; return data; }), catchError(err => { if (err.error && err.error.error && err.error.error.code) return of({ error: { '.tag': err.error.error.code.toString(), 'text': err.error.error.message } }); return of({ error: { '.tag': 'unknown_error' } }); })); }) ); } }