Angular http service tools

Angular http service tools can be divided into two versions, one is located @ angular / common / after service at http HttpClient located @ angular / Http service at http, before the v4.3 version Another version is v4.3. Specific differences can be viewed https://www.cnblogs.com/54hsh/p/11490711.html

 

Http service tools under 1, @ angular / http

import { Injectable }  from  "@angular/core";
import { Http, Response, RequestOptions, Headers }  from  '@angular/http';
import { Observable }  from  'rxjs/Observable';
import  'rxjs/add/operator/catch';
import  'rxjs/add/operator/map';

const options  =  new  RequestOptions({
  withCredentials:  true,
  headers:  new  Headers({  'X-Requested-With''XMLHttpRequest' })
});

@ Injectable()
export  class  HttpUtil {
   private baseUrl :  any;
   constructor( private  http :  Http) {
     this.baseUrl  =  'http://localhost:8080';
  }

   get( url :  string) {
     console. log( '发送get请求,url:', url)
    url  =  this.baseUrl  + url;
     return  this.http. get(url, options)
      . map( this.extractData)
      . catch( this.handleError);
  }

   post( url :  stringparams ?:  any) {
     console. log( '发送post请求,url:', url,  ',params:', params);
    url  =  this.baseUrl  + url;
     return  this.http. post(url, params, options)
      . map( this.extractData)
      . catch( this.handleError);
  }

   put( url :  stringparams ?:  any) {
     console. log( '发送put请求,url:', url,  ',params:', params);
    url  =  this.baseUrl  + url;
     return  this.http. put(url, params, options)
      . map( this.extractData)
      . catch( this.handleError);
  }

   delete( url :  string) {
     console. log( '发送delete请求,url:', url);
    url  =  this.baseUrl  + url;
     return  this.http. delete(url, options)
      . map( this.extractData)
      . catch( this.handleError);
  }

   postForm( url :  stringparams ?:  any) {
     let formData :  FormData  =  new  FormData();
    formData. append( 'username', params.username);
    formData. append( 'password', params.password);
     return  this. post(url, formData);
  }

   private  extractData( response :  Response) {
     console. log( '提取数据:', response);
     let body  = response. json();
     return body  || {};
  }

   private  handleError( error :  Response  |  any) {
     let errMsg :  string;
     if (error  instanceof  Response) {
       const body  = error. json()  ||  '';
       const err  = body.error  ||  JSON. stringify(body);
      errMsg  =  ` ${error.status }  -  ${error.statusText  ||  '' }   ${err } `;
    }  else {
      errMsg  = error.message  ? error.message  : error. toString();
    }
     console. error( '异常信息:', errMsg);
     return Observable. throw(errMsg);
  }

}

 

2、@angular/common/http下的HttpClient服务工具类

import { Injectable }  from  "@angular/core";
import { HttpClient, HttpHeaders }  from  '@angular/common/http';
import { Observable }  from  'rxjs';
import { map, catchError }  from  'rxjs/operators';

const options  = {
    headers:  new  HttpHeaders({ 'Content-Type''application/json'})
}

@ Injectable()
export  class  HttpClientUtil {
     private baseUrl :  any;

     constructor( private  httpClient :  HttpClient) {
         this.baseUrl  =  'http://localhost:8080';
    }

     public  get( url :  string) {
         console. log( '发送get请求,url:', url);
        url  =  this.baseUrl  + url;
         return  this.httpClient. get(url, options)
            . pipe( map( this.extractData),  catchError( this.handleError));
    }

     public  post( url :  stringparams ?:  any) {
         console. log( '发送post请求,url:', url,  ',params:', params);
        url  =  this.baseUrl  + url;
         return  this.httpClient. post(url, params, options)
            . pipe( map( this.extractData),  catchError( this.handleError));
    }

     public  put( url :  stringparams ?:  any) {
         console. log( '发送put请求,url:', url,  ',params:', params);
        url  =  this.baseUrl  + url;
         return  this.httpClient. put(url, params, options)
            . pipe( map( this.extractData),  catchError( this.handleError));
    }

     public  delete( url :  string) {
         console. log( '发送delete请求,url:', url);
        url  =  this.baseUrl  + url;
         return  this.httpClient. delete(url, options)
            . pipe( map( this.extractData),  catchError( this.handleError));
    }

     postForm( url :  stringparams ?:  any) {
         let formData :  FormData  =  new  FormData();
        formData. append( 'username', params.username);
        formData. append( 'password', params.password);
         return  this. post(url, formData);
    }

     private  extractData( response :  Response) {
         console. log( '提取数据:', response);
         let data  = response. json();
         return data  || {};
    }

     private  handleError( error :  Response  |  any) {
         let errMsg :  string;
         if (error  instanceof  Response) {
             const data  = error. json()  ||  '';
             const err  = data.toString  ||  JSON. stringify(data);
            errMsg  =  ` ${error.status }  -  ${error.statusText  ||  '' }   ${err } `;
        }  else {
            errMsg  = error.message  ? error.message  : error. toString();
        }
         console. error( '异常处理:', errMsg);
         return Observable. throw(errMsg);
    }
}

Guess you like

Origin www.cnblogs.com/54hsh/p/11512818.html