ionic简单封装http请求

1、ionic g service httpService
2、注册事件
//app.module.ts
import { HttpClientModule} from '@angular/common/http'
@NgModule({
  imports:[HttpClientModule]
})
3、在httpService.ts中写入请求逻辑
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
import { Storage } from "@ionic/storage";
import { appRestful } from '../appResfuls'

@Injectable({
  providedIn: 'root'
})
export class HttpserviceService {
  public token = ''
  public httpHeader: any = ''
  public commonUrl = ''
  constructor(
    public http: HttpClient,
    public storage: Storage,
  ) {

    this.commonUrl = appRestful.getProdUrl()
  }
  //封装get请求 需要两个参数
  async httpGet(url, params) {
    let commonUrl = this.commonUrl
    let httpOption
    await this.storage.get('authentication').then(val => {
      if (val) {
        httpOption = {
          headers: new HttpHeaders({
            'authentication': val
          }),
          params: params
        }
      } else {
        httpOption = {
          params: params
        }
      }
    })
    return await new Promise((resolve, reject) => {
      this.http.get(commonUrl + url, httpOption).subscribe((res) => {
        resolve(res)
      }, (err) => {
        reject(err)
      })
    })
  }

  //POTS请求 需要三个参数 
  async httpPost(url, params) {
    let httpOption
    await this.storage.get('authentication').then(val => {
      httpOption = {
        headers: new HttpHeaders({
          'authentication': val
        })
      }
    })
    return await new Promise((resolve, reject) => {
      this.http.post(this.commonUrl + url, params, httpOption).subscribe((res) => {
        resolve(res)
      }, (err) => {
        reject(err)
      })
    })
  }

  //PUT请求

  //DELETE请求
}

4、appResful.ts中放接口
export class appRestful{
    //定义接口地址
    public static interfaces={
        login:'/v4/authentications', //登录
    }
 
    //测试环境URL
    public static getDevUrl(){
        return 'http://192.168.1.171:9090'
    }
    //生产环境URL
    public static getProdUrl(){
        return 'http://prd9.hbjk.com.cn:8080'
    }
    
}

你可能感兴趣的:(ionic简单封装http请求)