Skip to content
Snippets Groups Projects
hospital.service.ts 2.02 KiB
Newer Older
import { Injectable } from '@angular/core';

import { AuthService } from './auth.service';
import { environment } from '../environments/environment';
import { catchError, map, tap } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Hospital } from './hospital';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Observable';
import { FormBuilder, FormGroup } from '@angular/forms';


@Injectable()
export class HospitalService {

  private hospitalURL = environment.webserviceUrl+"/api/data";
  //get: private hospitalURL = environment.webserviceUrl+"/api/data/listagents";

  httpOptions = { headers: new HttpHeaders({ }) };

  private updateHttpHeader() {
    this.httpOptions.headers = 
      this.httpOptions.headers.set('Authorization', this.authService.getToken());
   }

  private translateToServer(hospital: Hospital) {

    const formData = new FormData()
    formData.append('name', hospital.name)
    formData.append('latitude', hospital.latitude)
    formData.append('longitude', hospital.longitude)
    formData.append('city', hospital.city)
    formData.append('file', hospital.image, hospital.image.name)
    /*
    var send = {
      name: hospital.name,
      longitude: hospital.longitude,
      latitude: hospital.latitude,
      //countie: hospital.city,
      //state: hospital.state,
      //region: hospital.region,
    */
    return formData;

  }

  addHospital(hospital: Hospital): Observable<any> {
    if (this.authService.loggedIn()) { this.updateHttpHeader() }

    return this.http.post<any>(this.hospitalURL+"/agents", this.translateToServer(hospital), this.httpOptions)
      .pipe(tap(_ => console.log("added "+hospital.name)),
        catchError(this.handleError<Hospital>())
      );
  }

  private handleError<T> (result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      return Observable.of(result as T);
    }
  }

  constructor(private http: HttpClient,
              private authService: AuthService
              ) { }

}