ng-rest-http
Version:
http client module for Angular [ tested for angular6 ]
311 lines (305 loc) • 11.8 kB
JavaScript
import * as i0 from '@angular/core';
import { Injectable, NgModule } from '@angular/core';
import * as i1 from '@angular/common/http';
import { HttpParams, HttpHeaders, HttpRequest, HttpClientModule } from '@angular/common/http';
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
class RestHttpClient {
constructor(http) {
this.http = http;
}
/**
* @param Object obj {url, params, headers}
* url : String,
* params {k1:v1, k2:v2....}
* headers {k1:v1, k2:v2....}
* @return Callback Function
*/
get(obj) {
const apiUrl = obj.url;
const body = {};
body.observe = 'response';
if (!Object.entries) {
Object.entries = (entryObj) => {
const ownProps = Object.keys(entryObj);
let i = ownProps.length;
const resArray = new Array(i); // preallocate the Array
while (i--) {
resArray[i] = [ownProps[i], entryObj[ownProps[i]]];
}
return resArray;
};
}
if (typeof obj.params !== 'undefined') {
let Params = new HttpParams();
Object.entries(obj.params).forEach(([key, value]) => Params = Params.append(key, String(value)));
body.params = Params;
}
if (typeof obj.headers !== 'undefined') {
body.headers = this.createHeders(obj.headers);
}
return new Promise((resolve, reject) => {
this.http.get(apiUrl, body)
.pipe(
// 에러가 발생하면 err를 녀ㅠㄴㅊ갸ㅠㄷdml next 로 보낸다.
catchError(err => { return of(err); })
// catchError(this.handleError)
// catchError(err => {return of(this.handleError(err));})
)
.subscribe({
next: (v) => resolve(v),
error: (e) => reject(e),
complete: () => console.info('complete')
});
});
}
/**
* @param Object obj {url, params}
* @return Callback Function
*/
post(obj) {
const apiUrl = obj.url;
const params = obj.params;
const body = {};
body.observe = 'response';
if (typeof obj.headers !== 'undefined') {
body.headers = this.createHeders(obj.headers);
}
return new Promise((resolve) => {
this.http.post(apiUrl, params, body)
.subscribe({
next: (v) => resolve(v),
error: (e) => this.logError(e),
complete: () => console.info('complete')
});
});
}
/**
* @param Object obj {url, params}
* @return Callback Function
*/
delete(obj) {
const apiUrl = obj.url;
const body = {};
body.observe = 'response';
if (typeof obj.headers !== 'undefined') {
body.headers = this.createHeders(obj.headers);
}
return new Promise((resolve) => {
this.http.delete(apiUrl, body)
.subscribe({
next: (v) => resolve(v),
error: (e) => this.logError(e),
complete: () => console.info('complete')
});
});
}
/**
* @param Object obj {url, params}
* @return Callback Function
*/
update(obj) {
const apiUrl = obj.url;
const params = obj.params;
const body = {};
body.observe = 'response';
if (typeof obj.headers !== 'undefined') {
body.headers = this.createHeders(obj.headers);
}
return new Promise((resolve) => {
this.http.post(apiUrl, params, body)
.subscribe({
next: (v) => resolve(v),
error: (e) => this.logError(e),
complete: () => console.info('complete')
});
});
}
/**
* @param Object obj {url, params}
* @return Callback Function
*/
put(obj) {
const apiUrl = obj.url;
const params = obj.params;
const body = {};
body.observe = 'response';
if (typeof obj.headers !== 'undefined') {
body.headers = this.createHeders(obj.headers);
}
return new Promise((resolve) => {
this.http.put(apiUrl, params, body)
.subscribe({
next: (v) => resolve(v),
error: (e) => this.logError(e),
complete: () => console.info('complete')
});
});
}
/**
* @param Object headers : headers {k1:v1, k2:v2....}
*/
createHeders(headers) {
let header = new HttpHeaders(); // { 'Content-Type': 'application/json' }
if (!Object.entries) {
Object.entries = (entryObj) => {
const ownProps = Object.keys(entryObj);
let i = ownProps.length;
const resArray = new Array(i); // preallocate the Array
while (i--) {
resArray[i] = [ownProps[i], entryObj[ownProps[i]]];
}
return resArray;
};
}
Object.entries(headers).forEach(([key, value]) => header = header.append(key, String(value)));
return header;
}
extractData(res) {
try {
if (typeof res.constructor !== 'undefined' && res.constructor.name === 'HttpResponse') {
return res.body;
}
else {
const body = res.json();
return body || {};
}
}
catch (e) {
return res._body;
}
}
handleError(error) {
if (error.status === 0) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error);
}
else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(`Backend returned code ${error.status}, body was: `, error.error);
}
return error;
// return throwError(() => new Error('Something bad happened; please try again later.'));
}
logError(err) {
console.error('There was an error: ');
console.error(err);
}
/**
* Not yet tested
* @param Object obj {url, params, headers}
* url : String,
* params {k1:v1, k2:v2....}
* headers {k1:v1, k2:v2....}
* @return Callback Function
* @param String filetype application/ms-excel image/jpeg, image/png, and image/svg+xml.
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
*/
filedownload(obj, filetype) {
const apiUrl = obj.url;
const body = {};
body.observe = 'response';
body.responseType = 'arraybuffer'; // add responseType
if (!Object.entries) {
Object.entries = (entryObj) => {
const ownProps = Object.keys(entryObj);
let i = ownProps.length;
const resArray = new Array(i); // preallocate the Array
while (i--) {
resArray[i] = [ownProps[i], entryObj[ownProps[i]]];
}
return resArray;
};
}
if (typeof obj.params !== 'undefined') {
let Params = new HttpParams();
Object.entries(obj.params).forEach(([key, value]) => Params = Params.append(key, String(value)));
body.params = Params;
}
if (typeof obj.headers !== 'undefined') {
body.headers = this.createHeders(obj.headers);
}
if (typeof obj.headers !== 'undefined') {
this.createHeders(obj.headers);
}
return new Promise((resolve) => {
this.http.get(apiUrl, body)
.pipe(
// catchError(this.handleError)
catchError(err => { return of(err); })
// catchError(err => {return of(this.handleError(err));})
)
.subscribe({
next: (v) => resolve(v.body),
error: (e) => this.logError(e),
complete: () => console.info('complete')
});
});
}
/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data, type) {
const blob = new Blob([data], { type });
const url = window.URL.createObjectURL(blob);
const pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed === 'undefined') {
console.log('Please disable your Pop-up blocker and try again.');
}
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClient, deps: [{ token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClient }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClient, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: i1.HttpClient }]; } });
class UploadService {
constructor(http) {
this.http = http;
}
// file from event.target.files[0]
uploadFile(url, file) {
const formData = new FormData();
formData.append('upload', file);
const params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
/*
const options = {
headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
params: params,
reportProgress: true,
withCredentials: true,
}
*/
const req = new HttpRequest('POST', url, formData, options);
return this.http.request(req); // return event
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: UploadService, deps: [{ token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: UploadService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: UploadService, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: i1.HttpClient }]; } });
class RestHttpClientModule {
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClientModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClientModule, imports: [HttpClientModule] }); }
static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClientModule, providers: [RestHttpClient, UploadService], imports: [HttpClientModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.1.4", ngImport: i0, type: RestHttpClientModule, decorators: [{
type: NgModule,
args: [{
imports: [HttpClientModule],
providers: [RestHttpClient, UploadService]
}]
}] });
/**
* Generated bundle index. Do not edit.
*/
export { RestHttpClient, RestHttpClientModule, UploadService };
//# sourceMappingURL=ng-rest-http.mjs.map