Posts

Showing posts with the label Angular Httpclient

Angular (5) Httpclient Observe And ResponseType: 'blob'

Answer : When using observe:response , don't type the call ( post<Blob>(...) ), as the returned Observable will be of HttpResponse. So this should work: this.httpclient.post('MyBackendUrl', params, {observe: 'response', responseType: 'blob'} ); Why this happens, is there's two versions of the post method, one with a generic type, one without: /** * Construct a POST request which interprets the body as JSON and returns the full event stream. * * @return an `Observable` of all `HttpEvent`s for the request, with a body type of `T`. */ post<T>(url: string, body: any | null, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: 'events'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean...

Angular: How To Download A File From HttpClient?

Answer : Blobs are returned with file type from backend. The following function will accept any file type and popup download window: downloadFile(route: string, filename: string = null): void{ const baseUrl = 'http://myserver/index.php/api'; const token = 'my JWT'; const headers = new HttpHeaders().set('authorization','Bearer '+token); this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe( (response: any) =>{ let dataType = response.type; let binaryData = []; binaryData.push(response); let downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType})); if (filename) downloadLink.setAttribute('download', filename); document.body.appendChild(downloadLink); downloadLink.click(); }...