import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { ConfigureUrl } from '../models'; import { AppSettingService } from './appsetting'; @Injectable({ providedIn: 'root' }) export class HttpUtility { private baseApiUrl: string = ""; constructor(private http: HttpClient, private appSetting :AppSettingService, private router: Router) { } /** * getFile * @param url */ public getFileAsText(url: string): Observable { return this.http .get(this.getApiUrl(url), { responseType: 'blob' as 'text' }) .pipe(catchError(e => this.handleError(e))); } /** * getFile * @param url */ public getFile(url: string): Observable { return this.http .get(this.getApiUrl(url), { responseType: 'blob' as 'json' }) .pipe(catchError(e => this.handleError(e))); } /** * handleError * @param response */ private handleError(errorResponse: HttpErrorResponse) { // in a real world app, we may send the server to some remote logging infrastructure // instead of just logging it to the console return throwError(errorResponse); } //get excel file zip file etc .. /* allowedToDisplay = [ this.mimeConstant.png, this.mimeConstant.jpeg, this.mimeConstant.jpg, this.mimeConstant.gif, this.mimeConstant.txt, this.mimeConstant.pdf ]; */ /* how to use it this.http.getFileResponse(`Person/GetPhoto?recordId=${personId}`).pipe( catchError(err => { this.snackBar.error(err || this.constants.error_Getting_photo); return EMPTY; }), finalize(() => { this.spinner.hide(); })).subscribe(response => { if (response) { if (isDownload) { CommonUtilities.downloadFile(response); } else { if (response.body && response.body.type) { if (this.allowedToDisplay.includes(response.body.type)) { CommonUtilities.displayFileInNewTab(response); } else { this.temporaryFile = response; this.downloadWarning = true; } } } } }); */ public getFileResponse(url: string, data?: any): Observable { if (data) { return this.http.post(this.getApiUrl(url), data, { responseType: 'blob', observe: 'response' }) .pipe(catchError(e => this.handleError(e))); } return this.http .get(this.getApiUrl(url), { responseType: 'blob', observe: 'response' }) .pipe(catchError(e => this.handleError(e))); } public getFileAsPDF(url: string, data: any): Observable { let updateURL; if (data) { updateURL = url + data; } else { updateURL = url; } return this.http .get(this.getApiUrl(updateURL), { responseType: 'blob' as 'text', observe: 'response' }) .pipe(catchError(e => this.handleError(e))); } /** * getApiUrl * @param url */ private getApiUrl(url:string) { const baseUrl = this.appSetting.appSetting.baseUrl; return baseUrl + "/"+ url; } }