ionic3 封装http请求

一,使用命令行创建服务

ionic g provider my-http

在app.moudule.ts中引入 MyHttpProvider

import { MyHttpProvider} from '../providers/my-http/my-http';
@NgModule({
  declarations: [
  ],
  imports: [
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
       MyHttpProvider
  ]
})
export class AppModule {}

 

二,封装方法

my-http.ts

import { HttpClient, HttpParams ,HttpHeaders} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { isObject } from "rxjs/util/isObject";
import { HOST_URL, ACCESS_TOKEN} from '../../domain/constants';  //HOST_URL访问地址,token
import {Loading, LoadingController} from "ionic-angular";


@Injectable()
export class MyHttpProvider {
  private loading: Loading;
  constructor(public http: HttpClient,private loadingCtrl: LoadingController) {
    console.log('Hello MyHttpProvider Provider');
  }
  /*带有token的get请求*/
  get(url: string, params: any, isShowLoading?:boolean, callback?: (res: any, error: any) => void): void {
    if (isShowLoading != null){
      if (isShowLoading){
        this.showLoading()
      }
    }
    let Url = `${HOST_URL}${url}/${localStorage.getItem(ACCESS_TOKEN)}`;
    let headers = new HttpHeaders();
    headers.append('token', localStorage.getItem(ACCESS_TOKEN));
    this.http.get(Url, {params: this.encodeComplexHttpParams(params),
    headers:headers})
      .subscribe(res => {
        this.hideLoading()
        callback && callback(res, null);
      }, error => {
        this.hideLoading()
        callback && callback(null, error);
      });
  }

  /*带有token的post请求*/
  post(url: string, params: any,isShowLoading?:boolean, callback?: (res: any, error: any) => void): void {
    if (isShowLoading != null){
      if (isShowLoading){
        this.showLoading()
      }
    }
    let Url = `${HOST_URL}${url}/${localStorage.getItem(ACCESS_TOKEN)}`;
    let headers = new HttpHeaders();
    headers.append('token', localStorage.getItem(ACCESS_TOKEN));
    console.log(localStorage.getItem(ACCESS_TOKEN))
    this.http.post(Url, this.encodeComplexHttpParams(params),{
      headers:headers
    })
      .subscribe(res => {
          this.hideLoading()
          callback && callback(res, null);
      },
        error => {
          this.hideLoading()
          callback && callback(null, error);
        });
  }

  /*不带有token的get请求*/
  getDirect(url: string, params: any,isShowLoading?:boolean, callback?: (res: any, error: any) => void): void {
    if (isShowLoading != null){
      if (isShowLoading){
        this.showLoading()
      }
    }
    let Url = HOST_URL + url;
    this.http.get(Url, { params: this.encodeComplexHttpParams(params) })
      .subscribe(res => {
        this.hideLoading()
        callback && callback(res, null);
      }, error => {
        this.hideLoading()
        callback && callback(null, error);
      });
  }

  /*不带有token的post请求*/
  postDirect(url: string, params: any, isShowLoading?:boolean,callback?: (res: any, error: any) => void): void {
    if (isShowLoading != null){
      if (isShowLoading){
        this.showLoading()
      }
    }
    let Url = HOST_URL + url;
    this.http.post(Url, this.encodeComplexHttpParams(params))
      .subscribe(res => {
        this.hideLoading()
          callback && callback(res, null);
        },
        error => {
          this.hideLoading()
          callback && callback(null, error);
        });
  }

  private paramsString(params: any): string {
    if (!params) return null; let str = "";
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        let value = params[key];
        if (value === null) continue;
        if (Array.isArray(value)) {
          if (value.length === 0) continue;
          for (let index = 0; index < value.length; index++) {
            let k = key + "[" + index + "]"; let v = value[index];
            if (str.length > 1) str += "&"; str += k + "=" + v;
          }
        } else if (isObject(value)) {
          for (let subKey in value) {
            if (value.hasOwnProperty(subKey)) {
              let v = value[subKey];
              if (v === null) continue; let k = key + "[" + subKey + "]";
              if (str.length > 1) str += "&"; str += k + "=" + v;
            }
          }
        }
        else { if (str.length > 1) str += "&"; str += key + "=" + value; }
      }
    }
    return str;
  }

  private encodeComplexHttpParams(params: any): any {
    if (!params) return null;
    return new HttpParams({ fromString: this.paramsString(params) });
  }

/*打开loading*/
  showLoading(content = ''): void {
    if (!this.loading) {
      const loading = this.loadingCtrl.create({
      })
      loading.present();
      this.loading = loading;
     
    }
  }

  /*关闭loading*/
  hideLoading(): void {
    this.loading && this.loading.dismiss();
    this.loading = null;
  }

三,模块使用

在需要请求http的页面使用

import { Component } from '@angular/core';
import {IonicPage,  NavController,} from 'ionic-angular';
import { MyHttpProvider } from "../../providers/my-http/my-http";
import { HOST_URL} from "../../domain/constants";

@IonicPage()
@Component({
  selector: 'page-my',
  templateUrl: 'my.html'
})
export class MyPage {
 constructor(public  navCtrl: NavController,
              public MyHttp:MyHttpProvider,
              ) { 
}

ionViewDidEnter(){
    this.GetInfo(); //http请求
}
GetInfo(){
    this.MyHttp.post(' ………………接口',{参数},
      true,(res,error)=>{
        if(res){
            请求结果处理
        }
    })
}



}

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值