import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable , throwError } from 'rxjs' ; import { catchError , retry } from 'rxjs/operators' ; import { defaultUrlConfig } from '../shared/url-config' ; import { SuggestResponse } from '../models/api-suggest' ; import { hashtagRegExp } from './../utils/reg-exp' ; @ Injectable ( ) export class SuggestService { private static minified_results = true ; private static order = 'desc' ; private static orderby = 'query_count' ; private static count = '4' ; constructor ( private http ) { } public fetchQuery ( query ) { let jsonpUrl = defaultUrlConfig . loklak . apiServer + '/api/suggest.json' ; if ( hashtagRegExp . exec ( query ) !== null ) { jsonpUrl += '?callback=JSONP_CALLBACK&q=' + query ; } else { jsonpUrl += '?q=' + query + '&count=' + SuggestService . count + '&minified=' + SuggestService . minified_results . toString ( ) + '&order=' + SuggestService . order + '&orderby=' + SuggestService . orderby ; } return this . http . jsonp < SuggestResponse > ( jsonpUrl , 'callback' ) . pipe ( retry ( 2 ) , catchError ( this . handleError ) ) ; } private handleError ( error ) { const errMsg = ( error . message ) ? error . message : error . status ? `${ error . status } - ${ error . statusText }` : 'Server error' ; console . error ( errMsg ) ; return throwError ( errMsg ) ; } }