基于angular的HttpClient封装_HttpClient
电脑版发表于:2020/12/23 14:06
基于angular的HttpClient封装_HttpClient,直接复制源码即可用
包含常用的get、post、patch、delete和put请求;
import { HttpClient, HttpEvent, HttpHeaders, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of, throwError } from 'rxjs';
import { catchError, switchMap, tap } from 'rxjs/operators';
export type _HttpHeaders = HttpHeaders | { [header: string]: string | string[] };
/**
* 封装HttpClient,主要解决:
* + 优化HttpClient在参数上便利性
* + 统一实现 loading
*/
@Injectable({ providedIn: 'root' })
export class _HttpClient {
constructor(private http: HttpClient) {
}
private _loading = false;
/** 是否正在加载中 */
get loading(): boolean {
return this._loading;
}
private begin(): void {
Promise.resolve(null).then(() => (this._loading = true));
}
private end(): void {
Promise.resolve(null).then(() => (this._loading = false));
}
/**
* GET:返回一个 `any` 类型
*/
get(
url: string,
params?: any,
options?: {
headers?: _HttpHeaders;
observe?: 'body';
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
},
): Observable<any> {
this.begin();
return of(null).pipe(
tap(() => this.begin()),
switchMap(() => this.http.get(url, options)),
tap(() => this.end()),
catchError(res => {
this.end();
return throwError(res);
}),
);
}
/**
* POST:返回一个 `any` 类型
*/
post(
url: string,
body?: any,
params?: any,
options?: {
headers?: _HttpHeaders;
observe?: 'body';
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
},
): Observable<any> {
this.begin();
return of(null).pipe(
tap(() => this.begin()),
switchMap(() => this.http.get(url, options)),
tap(() => this.end()),
catchError(res => {
this.end();
return throwError(res);
}),
);
}
/**
* DELETE:返回一个 `any` 类型
*/
delete(
url: string,
params?: any,
options?: {
headers?: _HttpHeaders;
observe?: 'body';
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
},
): Observable<any> {
this.begin();
return of(null).pipe(
tap(() => this.begin()),
switchMap(() => this.http.get(url, options)),
tap(() => this.end()),
catchError(res => {
this.end();
return throwError(res);
}),
);
}
/**
* PATCH:返回一个 `any` 类型
*/
patch(
url: string,
body?: any,
params?: any,
options?: {
headers?: _HttpHeaders;
observe?: 'body';
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
},
): Observable<any> {
this.begin();
return of(null).pipe(
tap(() => this.begin()),
switchMap(() => this.http.get(url, options)),
tap(() => this.end()),
catchError(res => {
this.end();
return throwError(res);
}),
);
}
/**
* PUT:返回一个 `any` 类型
*/
put(
url: string,
body?: any,
params?: any,
options?: {
headers?: _HttpHeaders;
observe?: 'body';
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
},
): Observable<any> {
this.begin();
return of(null).pipe(
tap(() => this.begin()),
switchMap(() => this.http.get(url, options)),
tap(() => this.end()),
catchError(res => {
this.end();
return throwError(res);
}),
);
}
}