Ionic2实战-Http请求模块设计

前言

对于大部分App来说,都有大量前后端交互的需求,而Ionic2基于AngularJS2也提供了完善的Http通信模块,可以让我们方便地进行前后台的通信。

步骤

Http通信作为业务模块都写在了service文件中,以下步骤都是针对service的操作。

1、导入相关包

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、准备Http请求发送函数

  loadProductPriceList(params): Promise {
    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、调用发送函数

  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 {
    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);
  }
}

你可能感兴趣的:(Ionic2实战-Http请求模块设计)