Skip to content

Instantly share code, notes, and snippets.

@ZXS66
Created July 23, 2022 01:53
Show Gist options
  • Save ZXS66/b31d4f513ee5d19846742844d6260921 to your computer and use it in GitHub Desktop.
Save ZXS66/b31d4f513ee5d19846742844d6260921 to your computer and use it in GitHub Desktop.
Angular service base class
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
/** common request options */
const _HTTP_OPTIONS = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
}),
// withCredentials: true
};
/** get request body by formData (object type) */
function getRequestBody(formData: object) {
if (formData) {
const obj = getURLSearchParams(formData);
return obj.toString();
}
}
/**
* constructe URLSearchParams by form data(obejct)
* limitation: not support complicated form data, namely the properties of form data should be primitive type
*/
function getURLSearchParams(formData: object): URLSearchParams {
const params = new URLSearchParams();
if (formData) {
Object.keys(formData).forEach(p => {
const val = formData[p];
if (Array.isArray(val)) {
// workaround 1: make sure the item of the array are primitive type (work in front-end)
val.forEach(v => {
params.append(p, typeof (v) === 'object' ? JSON.stringify(v) : v);
});
// // workaround 2: cast array type to string type(deserialize it in server side)
// params.append(p, JSON.stringify(val));;
} else if (typeof val !== 'object') {
params.append(p, val);
}
});
}
// // append timestamp to the form body to force query (ignore cache/Relativity platform/server cache)
// params.append('t', Date.now().toString());
return params;
}
export class BaseService {
constructor(
private http: HttpClient
) {
this.BASE_URL = '/your-app-root-path-here/';
}
/** ApiController URL */
private BASE_URL: string;
/** sending post request to API */
_post(actionName: string, formData?: object): Observable<any> {
// const url = this._baseURL + actionName;
const url = `${this.BASE_URL}${actionName}/${Math.round(performance.now())}`;
return this.http.post(
url,
getRequestBody(formData), // custom
_HTTP_OPTIONS // options
).pipe(take(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment