Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This function can be used to get files from angular observable
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { TokenManager } from "@app/shared/services/token-manager.service";
@Injectable()
export class ApiHandler {
constructor(private http: HttpClient) {}
apiGet(url, params?, extras?: Extras) {
let options = this.renderHeaders(extras);
options = this.appendParams(options, params);
return this.http.get(url, options).timeout(30000);
}
apiPost(url, reqBody, extras?: Extras) {
const options = this.renderHeaders(extras);
return this.http.post(url, reqBody, options).timeout(30000);
}
apiUpdate(url, reqBody, extras?: Extras) {
const options = this.renderHeaders(extras);
return this.http.put(url, reqBody, options).timeout(30000);
}
apiDelete(url, extras?) {
const options = this.renderHeaders(extras);
return this.http.delete(url);
}
private renderHeaders(extras: Extras) {
// if extras is present then apply check
if (extras) {
if (extras.contentType.isFormDataContent) {
return {};
}
} else {
// else assume it to be json data
return {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
// headers: new HttpHeaders({
// "Content-Type": "application/xml"
// })
};
}
}
getHttpRequester() {
return this.http;
}
private appendParams(originalOptions, paramsObj) {
let params = new HttpParams();
for (let key in paramsObj) {
if (paramsObj.hasOwnProperty(key)) {
if (key === "offset") {
const val = paramsObj[key] / 10;
params = params.append("page_num", val.toString());
} else {
params = params.append(key, paramsObj[key]);
}
}
}
return Object.assign({}, originalOptions, { params: params });
}
}
testFun(excelDownloadUrl) {
this.apiHandler
.getHttpRequester()
.get("http://192.168.0.243:3000/api/admin/report/user", {
responseType: "blob"
})
.subscribe(data => {
console.log(data);
const blob: any = new Blob([data], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
// blob.name = "user-report.xlsx"
var url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "user-report";
a.style.display = "none";
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
});
}
// call the function on some button click
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment