ionic3请求封装

1 篇文章 0 订阅
1 篇文章 0 订阅
  1. 引入对应依赖以及方法
	import { Storage } from '@ionic/storage';
	import { HttpClient ,HttpHeaders} from '@angular/common/http';
	import { Injectable } from '@angular/core';
	import { config } from '../api/config'
	@Injectable()
  1. 变量申明、头部以及对应方法
	//token和请求地址
    accessToken = '';
    url = 'https://xx.xx.com';
    //头部
    private buildHeader() {
        let header = {
            'Authorization': 'Bearer ' + this.accessToken,
            'Content-Type': 'application/json'
        };
        return header;
    }
    //从storage获取token
    public getToken(){
      this.storage.get('access_token_idoc').then(token => {
        this.accessToken = token;
      })
    }
    //get方法
    public get(urlmethod , callback ?: (res: any, error: any) => void): void  { 
      this.getToken()
      this.config.show('加载中')
      this.http.get(this.url + urlmethod,{ headers: this.buildHeader() }).subscribe(data =>{ 
        this.config.hide()
        callback && callback(data, null);
      },err =>{
        this.handleError(err.status)
      })
    }
    //delete
    public delete(urlmethod , callback ?: (res: any, error: any) => void): void  { 
      this.getToken()
      this.config.show('加载中')  
      this.http.delete(this.url + urlmethod,{ headers: this.buildHeader() }).subscribe(data =>{ 
        callback && callback(data, null);
        this.config.hide()
      },err =>{
        this.handleError(err.status)
      })
    }
    //put
    public put(urlmethod ,data, callback ?: (res: any, error: any) => void): void  {   
      this.getToken() 
      this.config.show('加载中')  
      this.http.put(this.url + urlmethod, data, {headers: this.buildHeader()})        
      .subscribe(res => { 
          callback && callback(res, null);
          this.config.hide()
      },err =>{
        this.handleError(err.status)
      })     
    }
    //post
    public post(urlmethod ,data, callback ?: (res: any, error: any) => void): void  {   
      this.getToken()  
      this.config.show('加载中')
      this.http.post(this.url + urlmethod, data, {headers: this.buildHeader()})        
      .subscribe(res => { 
        this.config.hide()
        callback && callback(res, null);
      },err =>{
        this.handleError(err.status)
      })    
    }
  1. 错误处理
    public handleError(status){
      this.config.hide()
      switch (status) {
          case 401:
              this.config.tip('用户未登录')
              break;
          case 403:
              this.config.tip('登录过期,请重新登录')
              break;
          case 404:
              this.config.tip('网络请求不存在')
              break;
          default:
              this.config.tip('服务器请求错误')
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值