angular4 http服务封装 用的是rxjs

http.base.ts

第一步引入rxjs

    import "rxjs/add/operator/toPromise";
    import { RequestOptions ,Headers ,Http,Response ,URLSearchParams } from "@angular/http";

第二步建一个构造函数

    constructor(private http:Http){
        
    }

第三步封装post请求

    public post(url,data,headerType){
    console.log(data);
    let headers = new Headers();//构建一个header头的对象
    console.log(headers);
    if(headerType == "json"){
      headers.append("Content-type","application/json"); //在headers头里面增加一个对象
    }
    if(headerType == "urlencoded"){
      headers.append("Content-type","application/x-www-form-urlencoded");
    }
    if(headerType == "formdata"){
      headers.append("Content-type","multipart/form-data")
    }
    console.log(headers);
    return this.http.post(url,data,{headers:headers,withCredentials:true}).map((res:Response)=>{
      return res.json()//可以在这里面做错误信息的处理
        
    }).catch(err =>{
      throw console.log(err)
    })

}

第四步在业务操作里面引入这个函数 orderManage.component.ts

import {HttpInterceptorService } from "../base/network/http.base";
private getHttp(){
this.HttpInterceptorService.post("https://twms.gxcards.com/app/cmsUser/channelStatus",{},"json").subscribe((res:Response)=>{
  console.log(res)
})

}

猜你喜欢

转载自my.oschina.net/u/3312137/blog/1794161