阅读背景:

angular HtttClient 封装

来源:互联网 


import { Injectable } from '@angular/core';

import { environment } from '../../../environments/environment';
import {
  HttpHeaders,
  HttpClient,
  HttpErrorResponse
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { throwError } from 'rxjs';

@Injectable()
export class LocalHttp {
  // 获取API地址前缀
  public localUrl = environment.localApi;
  // 默认请求头设置
  public HttpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };
  constructor(
    private http: HttpClient,
    private router: Router,
    private message: NzMessageService
  ) {}
  /**
   * post请求
   * @param reqdata 请求参数
   * @param url 请求地址
   * @param callBack 成功回调
   * @param errorBack 异常回调
   */

  post(reqdata: any, url: any, callBack: any, errorBack: any) {
    this._post(reqdata, url).subscribe(
      res => {
        if (callBack) {
          callBack(res);
        }
      },
      error => {
        if (errorBack) {
          errorBack(error);
        } else {
          this._error(error);
        }
      }
    );
  }

  /**
   * get 请求
   * @param url 请求地址
   * @param callBack 成功回调
   * @param errorBack 异常回调
   */
  get(url: any, callBack: any, errorBack: any) {
    this._get(url).subscribe(
      res => {
        if (callBack) {
          callBack(res);
        }
      },
      error => {
        if (errorBack) {
          errorBack(error);
        } else {
          this._error(error);
        }
      }
    );
  }
  /**
   * post请求 (自定义头可用该方法)
   * @param reqdata 请求参数
   * @param url 请求地址
   * @param headers 请求头
   */
  _post(reqdata, url: any, headers?) {
    let _url = this.localUrl + url;

    // 自定义请求头
    if (headers) {
      this._setHeader(headers);
    }

    return this.http.post(_url, reqdata, this.HttpOptions).pipe(
      // 网络异常 再次发送请求(会连发三次)
      // retry(3),
      catchError(this.handleError)
    );
  }

  /**
   * get请求
   * @param url 请求地址
   */
  _get(url) {
    let _url = this.localUrl + url;

    return this.http.get(_url).pipe(
      // 网络异常 再次发送请求(会连发三次)
      // retry(1),
      catchError(this.handleError)
    );
  }

  /**
   * 默认异常处理
   * @param err 异常对象体
   */
  _error(err) {
    let msg = err.error;
    this.message.create('error', msg['Message']);
    // 认证异常
    if (err.status == '401') {
      this.router.navigate(['login']);
    }
  }
  /**
   * 自定义请求头
   * @param headers 请求头
   */
  _setHeader(headers) {
    for (const key in headers) {
      if (headers.hasOwnProperty(key)) {
        const element = headers[key];
        this.HttpOptions.headers = this.HttpOptions.headers.set(key, element);
      }
    }
  }

  // 异常拦截
  private handleError(error: HttpErrorResponse) {
    console.log(error);

    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Status code ${error.status}, ` +
        `ActionRequestID was: ${error.error.ActionRequestID}, ` +
        `Message was: ${error.error.Message}`
    );
    // return an observable with a user-facing error message
    return throwError(error);
  }
}

import { Injectable } from 



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: