美文网首页
Angular httpclient简单封装

Angular httpclient简单封装

作者: 默默无闻的小人物 | 来源:发表于2021-09-28 07:06 被阅读0次
    import { Injectable, Injector } from '@angular/core';
    import { Observable, Subscriber } from 'rxjs';
    import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
    import { Router } from '@angular/router';
    import { TokenService } from '../interceptor/token/token.service';
    
    const TYPE = {
        ERROR: 'error',
        WARNING: 'warning',
        SUCCESS: 'success'
    };
    
    @Injectable()
    export class HttpUtils {
    
    
        _options = {
            observe: 'response',
            responseType: 'json'
        };
        _messageId;
        private _loading = false;
    
         /** 是否正在加载中 */
        get loading(): boolean {
            return this._loading;
        }
    
        private parseParams(params: any): HttpParams {
            let ret = new HttpParams();
            if (params) {
                for (const key in params) {
                    if (params[key] !== undefined) { // 如果是undefault不传
                        const _data = params[key];
                        // // 将时间转化为:时间戳 (秒)
                        // if (moment.isDate(_data))
                        //     _data = moment(_data).unix();
                        ret = ret.set(key, _data);
                    }
                }
            }
            return ret;
        }
    
        private request<T>(method: string, url: string, options?: RequestOption): Observable<HttpResponse<T>> {
            const opt = this.options(options);
            const myObservable = this.http.request(method, url, opt);
            return Observable.create((observer: Subscriber<HttpResponse<T>>) => {
                myObservable.subscribe({
                    next: (response: HttpResponse<T>) => {
                        observer.next(response);
                    },
                    error: (response: HttpErrorResponse) => {
                        // this.handleError(opt, response);
                        observer.error(response);
                    },
                    complete: () => { // 发错误了之后不跳complete了
                        observer.complete();
                    }
                });
            });
        }
    
        // private handleError(opt, response: HttpErrorResponse) {
        //     if (opt.handleError) {
        //         switch (response.status) {
        //             case 400: {
        //                 const error: any = response.error;
        //                 this.error(error.error_description, TYPE.ERROR, opt.autoMessage);
        //                 if (error && error.code === 'invalid_token') {
        //                     this.goLogin();
        //                 }
        //                 break;
        //             }
        //             case 401: {
        //                 let message = 'Unauthorized';
        //                 let type = TYPE.ERROR;
        //                 if (response.error.error === 'invalid_token') {
        //                     message = 'Session expired, please log in again.';
        //                     type = TYPE.WARNING;
        //                 }
        //                 this.error(message, type);
        //                 this.goLogin();
        //                 break;
        //             }
        //             case 403: {
        //                 this.error('Forbidden');
        //                 break;
        //             }
        //             case 500: {
        //                 if (response.error && response.error === 'invalid_token') {
        //                     this.error('Unauthorized');
        //                     this.goLogin();
        //                     break;
        //                 }
        //                 this.error('Internal Server Error');
        //                 break;
        //             }
        //         }
    
        //     }
        // }
    
        private options(options: RequestOption) {
            return Object.assign({ handleError: true }, options, this._options);
        }
    
        private error(message, type = TYPE.ERROR, display: boolean = true) {
            if (!display) {
                return;
            }
            // 一秒钟内,多个请求只出错,只提示第一个错误
            if (!this._messageId) {
                // this._messageId = this.injector.get(NzMessageService).create(type, message); // 提示错误信息
                setTimeout(() => {
                    this._messageId = null;
                }, 1000);
            }
        }
    
        get<T>(url: string, params?, options: RequestOption = <RequestOption>{}): Observable<HttpResponse<T>> {
            options.urlParams = this.parseParams(params);
            return this.request<T>('get', url, options);
        }
    
        post<T>(url: string, body?, options: RequestOption = <RequestOption>{}): Observable<HttpResponse<T>> {
            options.body = this.parseParams(body).toString();
            options.urlParams = this.parseParams(options.urlParams);
            return this.request<T>('post', url, options);
        }
    
        put<T>(url: string, body?, options: RequestOption = <RequestOption>{}): Observable<HttpResponse<T>> {
            options.body = this.parseParams(body).toString();
            options.urlParams = this.parseParams(options.urlParams);
            return this.request<T>('put', url, options);
        }
    
        delete<T>(url: string, body?, options: RequestOption = <RequestOption>{}): Observable<HttpResponse<T>> {
            options.body = this.parseParams(body).toString();
            options.urlParams = this.parseParams(options.urlParams);
            return this.request<T>('delete', url, options);
        }
    
        form<T>(url: string, options: RequestOption = <RequestOption>{}): Observable<HttpResponse<T>> {
            options.urlParams = this.parseParams(options.urlParams);
            options.body = this.parseParams(options.body).toString();
            const header = new HttpHeaders({ 'content-type': 'application/x-www-form-urlencoded' });
            const merge = Object.assign({}, options, { headers: header });
            return this.request<T>('post', url, merge);
        }
        /**
         * formData 上传文件
         * @param url 地址
         * @param data 选择的文件
         */
        upload(url: string, data: any) {
            const token = this.tokenService.access_token.access_token;
            const xhr = this.createXHR();
            const formData = new FormData();
            formData.append('file', data);
            const p = new Promise(function (resolve, reject) {
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Authorization', `Bearer ${token}`);
                xhr.onreadystatechange = function () {
                    const resultObj = xhr.responseText ? JSON.parse(xhr.responseText) : xhr.responseText;
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            resolve(resultObj);
                        } else {
                            reject(resultObj);
                        }
                    }
                };
                xhr.send(formData);
            });
            return p;
        }
    
        private createXHR() {
            let xhr = null;
            if (XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            }
            return xhr;
        }
    
        private goLogin() {
            // this.injector.get(SettingsService).clean();
            this.injector.get(TokenService).destroy();
            this.injector.get(Router).navigate(['/login']);
        }
    
        constructor(private http: HttpClient, private injector: Injector, private tokenService: TokenService) {
    
        }
    
    }
    
    export interface RequestOption {
        body?: any;
        headers?: HttpHeaders;
        reportProgress?: boolean;
        observe?: 'response';
        urlParams?: HttpParams;
        responseType?: 'json';
        withCredentials?: boolean;
        handleError?: boolean;
        autoMessage?: boolean;
    }
    

    相关文章

      网友评论

          本文标题:Angular httpclient简单封装

          本文链接:https://www.haomeiwen.com/subject/nycknltx.html