wanjingy.github.io / hw8 / frontend / src / app / search-form.service.ts
search-form.service.ts
Raw
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SearchFormService {

  constructor(private http: HttpClient) { }

  //rootUrl = '/api';
  rootUrl = '';

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

  getAutoFill(keyword: string|null): Observable<string[]>{
    if(keyword != null && keyword != ''){
      return this.http.get<string[]>(this.rootUrl + `/autofill/${keyword}`)
      .pipe(
        catchError(this.handleError([]))
      );
    }
    else return of([]);
  }

  getIPLocation(){
    return this.http.get('https://ipinfo.io/?token=4fd050f2c74c76')
      .pipe(
        map((ipInfos: any) => ipInfos.loc),
        catchError(this.handleError(''))
      );
  }

  getGoogleLocation(location: string|null|undefined){
    if(location != null && location != undefined){
      return this.http.get('https://maps.googleapis.com/maps/api/geocode/json', {params: {address: location, key: 'AIzaSyBv14IBvcxFRUVxwD_MdioMfL1Ey22GnXs'}})
      .pipe(
        map((locInfo: any) => {
          if(locInfo.status == 'OK'){
            return locInfo.results[0].geometry.location;
          }else if(locInfo.status == 'INVALID_REQUEST'){
            return {};
          }
        }),
        catchError(this.handleError({}))
      );
    }
    else return of({});
  }

  getEvents(searchQuery: any){
    return this.http.get(this.rootUrl + '/events', {params: searchQuery})
  }

  
}