引入对应依赖以及方法
import { Storage } from '@ionic/storage' ;
import { HttpClient ,HttpHeaders} from '@angular/common/http' ;
import { Injectable } from '@angular/core' ;
import { config } from '../api/config'
@Injectable ( )
变量申明、头部以及对应方法
//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)
} )
}
错误处理
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 ( '服务器请求错误' )
}
}