主要內(nèi)容
- http get 請求
- http post 請求
- 全局的工具類
新建一個http請求類服務
HttpService.ts
/**
* Created by Void on 2017/7/13.
*
* 網(wǎng)絡請求服務類
*/
import {Injectable} from '@angular/core';
import {
Http, Headers, RequestOptions, URLSearchParams, RequestOptionsArgs, RequestMethod
} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import {NativeServiceC} from "./NativeServiceC";
import {AlertController} from "ionic-angular";
import {APP_SERVE_URL} from "./Constants";
@Injectable()
export class HttpService {
constructor(public http:Http,
private nativeService:NativeServiceC,
private alertCtrl:AlertController) {
}
public request(url:string, options:RequestOptionsArgs) { //:Observable<Response>
url = HttpService.formatUrl(url);
this.optionsAddToken(options);
return Observable.create(observer => {
this.nativeService.showLoading();
this.http.request(url, options)
.map(res => res.json())
.subscribe(res => {
if (res.code == 200) {
observer.next(res.data);
} else {
this.requestFailed(url, options, {status: res.code});//處理請求失敗
}
}, err => {
this.requestFailed(url, options, err);//處理請求失敗
observer.error(err);
});
});
}
public get(url:string, paramMap:any = null) { //:Observable<Response>
return this.request(url, new RequestOptions({
method: RequestMethod.Get,
search: HttpService.buildURLSearchParams(paramMap)
}));
}
public post(url:string, body:any = null):Observable<any> {
return this.request(url, new RequestOptions({
method: RequestMethod.Post,
body: body,
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8'
})
}));
}
public jsonRpc(model:string, method:string, args:any, kwargs?:any):Observable<any> {
kwargs = kwargs || {};
kwargs.context = kwargs.context || {};
Object.assign(kwargs.context, {
lang: "zh_CN",
tz:"Asia/Hong_Kong"
});
let params = {
model: model,
method: method,
args: args,
kwargs: kwargs,
};
return this.request("http://101.200.124.206:4713/web/dataset/call_kw", new RequestOptions({
method: RequestMethod.Post,
body: this.jsonrpcBuildSender(params),
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8',
"X-Openerp-Session-Id": 'a6e881e882dff5ca206b916753601873690cfbab',
// "Authorization": "Basic " + btoa(`${null}`)
})
}));
}
public jsonRpcLogin(login: string, password: string,db?: string){
db = db || 'hospital-saas';
let params = {
db : db,
login : login,
password : password
};
return this.request("http://101.200.124.206:4713/web/session/authenticate",{
method:RequestMethod.Post,
body: this.jsonrpcBuildSender(params),
});
}
private jsonrpcBuildSender(params:Object):Object{
let option = {
jsonrpc: "2.0",
method: "call",
params: params, // payload
id:new Date().getTime()
};
return option;
}
/**
* 將對象轉(zhuǎn)為查詢參數(shù)
* @param paramMap
* @returns {URLSearchParams}
*/
private static buildURLSearchParams(paramMap):URLSearchParams {
let params = new URLSearchParams();
if (!paramMap) {
return params;
}
for (let key in paramMap) {
let val = paramMap[key];
// todo 暫時不處理時間
// if (val instanceof Date) {
// val = Utils.dateFormat(val, 'yyyy-MM-dd hh:mm:ss')
// }
params.set(key, val);
}
return params;
}
/**
* 處理請求失敗事件
* @param url
* @param options
* @param err
*/
private requestFailed(url:string, options:RequestOptionsArgs, err):void {
this.nativeService.hideLoading();
console.log('%c 請求失敗 %c', 'color:red', '', 'url', url, 'options', options, 'err', err);
let msg = '請求發(fā)生異常', status = err.status;
if (!this.nativeService.isConnecting()) {
msg = '請求失敗,請連接網(wǎng)絡';
} else {
if (status === 0) {
msg = '請求失敗,請求響應出錯';
} else if (status === 404) {
msg = '請求失敗分飞,未找到請求地址';
} else if (status === 500) {
msg = '請求失敗血久,服務器出錯,請稍后再試';
}
}
this.alertCtrl.create({
title: msg,
subTitle: '狀態(tài)碼:' + status,
buttons: [{text: '確定'}]
}).present();
}
/**
* url中如果有雙斜杠替換為單斜杠
* 如:http://88.128.18.144:8080//api//demo. 替換后http://88.128.18.144:8080/api/demo
* @param url
* @returns {string}
*/
private static formatUrl(url:string):string {
if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
url = APP_SERVE_URL + url;
}
let index = url.indexOf('//') + 2;
return url.substring(0, index) + url.substring(index).replace(/\/\//g, '/');
}
private optionsAddToken(options:RequestOptionsArgs):void {
let token = 'TOKEN'; //this.globalData.token;
if (options.headers) {
options.headers.append('token', token);
} else {
options.headers = new Headers({
'token': token
});
}
}
}
上面有幾個jsonrpc的方法可以忽略不看爸邢,是測試odoo后臺使用的
該文件中導入了 NativeServiceC服務咏花,所以需要有該服務。
新建一個NativeService工具類服務
NativeServiceC.ts
/**
* Created by Void on 2017/7/13.
*
* 調(diào)用手機硬件的類
*
* plugins: status splash network
*
*
*/
import {Injectable} from '@angular/core';
import {ToastController, LoadingController, Platform, Loading, AlertController} from 'ionic-angular';
import {StatusBar} from "@ionic-native/status-bar";
import {SplashScreen} from "@ionic-native/splash-screen";
import {Network} from '@ionic-native/network';
import {GlobalData} from './GlobalData'
@Injectable()
export class NativeServiceC {
private loading:Loading;
private loadingIsOpen:boolean = false;
constructor(private platform:Platform,
private toastCtrl:ToastController,
private alertCrl:AlertController,
private loadingCtrl:LoadingController,
private statusBar:StatusBar,
private splashScreen:SplashScreen,
private network:Network,
private globalData:GlobalData) {
}
log(info):void {
console.log('%cNativeService/' + info, 'color:#C41A16');
}
statusBarStyleDefault():void {
this.statusBar.styleDefault();
}
splashScreenHide():void {
this.splashScreen.hide();
}
getNetworkType():string {
if (!this.isMobile()) {
return 'wifi';
}
return this.network.type;
}
isConnecting():boolean {
return this.getNetworkType() != 'none';
}
isMobile():boolean {
return this.platform.is('mobile') && !this.platform.is('mobileweb');
}
isAndroid():boolean {
return this.isMobile() && this.platform.is('android');
}
isIos():boolean {
return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
}
alert(title:string):void {
this.alertCrl.create({
title:title,
buttons:[{text:'確定'}]
}).present();
}
/**
* 統(tǒng)一調(diào)用此方法顯示loading
* @param content 顯示的內(nèi)容
*/
showLoading(content:string = ''):void {
if (!this.globalData.showLoading){
return ;
}
if (!this.loadingIsOpen){
this.loadingIsOpen = true;
this.loading = this.loadingCtrl.create({
content:content
});
this.loading.present();
setTimeout(() => { // 最長顯示15s
this.loadingIsOpen && this.loading.dismiss();
this.loadingIsOpen = false;
},15000);
}
}
/**
* 關閉loading
*/
hideLoading():void {
if (!this.globalData.showLoading){
this.globalData.showLoading = true;
}
this.loadingIsOpen && this.loading.dismiss();
this.loadingIsOpen = false;
}
}
該服務中依賴了一些Cordova插件疙驾,別忘記導入
該文件中導入了 GlobalData 服務凶伙,所以還要新建該服務。
新建一個GlobalData全局變量設置類服務
GlobalData.ts
/**
* Created by Void on 2017/7/14.
* 保存全局的一些數(shù)據(jù)它碎,和單例的設置
*/
import { Injectable } from '@angular/core';
@Injectable()
export class GlobalData{
private _showLoading:boolean = true;
get showLoading(): boolean {
return this._showLoading;
}
set showLoading(value: boolean) {
this._showLoading = value;
}
}
HttpService的使用
- app.module.ts中引入HttpService和HttpModule
import {HttpModule} from '@angular/http';
import { HttpService } from '../providers/HttpService';
import { NativeServiceC } from '../providers/NativeServiceC';
import { GlobalData } from '../providers/GlobalData';
imports: [HttpModule],
providers: [
StatusBar,
SplashScreen,
Network,
HttpService,
NativeServiceC,
GlobalData,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
- 在某一個頁面的組件中使用
import {HttpService} from '../../providers/HttpService';
import {NativeServiceC} from "../../providers/NativeServiceC";
import {GlobalData} from "../../providers/GlobalData";
constructor(public navCtrl:NavController,
private httpService:HttpService,
private nativeService:NativeServiceC,
private globalData:GlobalData) { }
// 本次請求不顯示loading, 默認顯示
this.globalData.showLoading = false;
this.httpService.get(url, sender).subscribe(res => {
// 隱藏loading函荣,所有請求結(jié)束后都必須手動隱藏,不會自動隱藏扳肛。
this.nativeService.hideLoading();
console.log(res);
})