前言
對于大部分App來說,都有大量前后端交互的需求,而Ionic2基于AngularJS2也提供了完善的Http通信模塊,可以讓我們方便地進(jìn)行前后臺的通信。
步驟
Http通信作為業(yè)務(wù)模塊都寫在了service文件中,以下步驟都是針對service的操作。
1、導(dǎo)入相關(guān)包
import { Http, Headers, RequestOptions } from '@angular/http';
2、初始化header消息頭
headers: Headers;
requestOptions: RequestOptions;
constructor(
private events: Events,
private http: Http,
private helper: Helper
) {
this.headers = new Headers({'X-Requested-With': 'XMLHttpRequest'});
this.requestOptions = new RequestOptions({headers: this.headers, withCredentials: true});
}
3、準(zhǔn)備Http請求發(fā)送函數(shù)
loadProductPriceList(params): Promise<CoalPrice> {
let api: string = this.helper.getAPP('product/getProductPriceList');
let data: Object = params;
return this.http.post(api, data, this.requestOptions)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
// handle error
private handleError(error: any) {
return Promise.reject(error.message || error);
}
4、調(diào)用發(fā)送函數(shù)
loadProductPriceList(params) {
this.coalService.loadProductPriceList(params)
.then(ret => {
this.productPriceList = ret;
}, (data) => {
});
}
完整代碼附錄
import { Injectable } from '@angular/core';
import { Events } from 'ionic-angular';
import { Http, Headers, RequestOptions } from '@angular/http';
import { CoalPrice } from '../models/coalPrice.model';
import { Helper } from '../../common/services/helper.service';
@Injectable()
export class CoalService {
headers: Headers;
coalPrices: CoalPrice[] = [];
requestOptions: RequestOptions;
userUpdateAvatarAPI: string = this.helper.getAPI('user/update-avatar');
//
// constructor
constructor(
private events: Events,
private http: Http,
private helper: Helper
) {
this.headers = new Headers({'X-Requested-With': 'XMLHttpRequest'});
this.requestOptions = new RequestOptions({headers: this.headers, withCredentials: true});
}
getProductTypeList(data) {
let api: string = this.helper.getAPP('product/getProductTypeList');
return this.http.post(api, data, this.requestOptions)
.toPromise()
.then((response) => {
return response.json();
})
.catch(this.handleError);
}
//
loadProductPriceList(params): Promise<CoalPrice> {
let api: string = this.helper.getAPP('product/getProductPriceList');
let data: Object = params;
return this.http.post(api, data, this.requestOptions)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
//
// handle error
private handleError(error: any) {
return Promise.reject(error.message || error);
}
}