angular中的http请求封装

1、新建ts文件(工具类;HttpUtils.Service.ts)

/**
 * name:http服务
 * describe:对http请求做统一处理
 */
import {Injectable}    from '@angular/core';
import {Http, Response}   from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpInterceptorService {

  constructor(private http: Http) {
  }

  /**
   * 统一发送请求
   * @param params
   * @returns {Promise<{success: boolean, msg: string}>|Promise}
   */
  public request(params: any): any {
    // POST请求(参数、返回值类型都是任意类型)
    if (params['method'] == 'post' || params['method'] == 'POST') {
      return this.post(params['url'], params['data']);
    } else { // 其他请求
      return this.get(params['url'], params['data']);
    }
  }

  /**
   * get请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise|Promise}
   */
  public get(url: string, params: any): any {
    return this.http.get(url, {search: params})
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }

  /**
   * post请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise|Promise}
   */
  public post(url: string, params: any) {
    return this.http.post(url, params)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }

  /**
   * 处理请求成功
   * @param res
   * @returns {{data: (string|null|((node:any)=>any)
 */
  private handleSuccess(res: Response) {
    let body = res["_body"];
    // console.log("接口返回的成功信息:" + body)
    if (body) { // 有数据返回
      return {
        data: res.json().data || {}, // 返回内容
        code: res.json().code || {}, // 返回code
        message: res.json().message || {}, // 返回信息
        statusText: res.statusText,
        status: res.status,
        success: true
      }
    } else { // 无数据返回
      return {
        data: res.json().data || {}, // 返回内容
        code: res.json().code || {}, // 返回code
        message: res.json().message || {}, // 返回信息
        statusText: res.statusText,
        status: res.status,
        success: true
      }
    }
  }

  /**
   * 处理请求错误
   * @param error
   * @returns {void|Promise|Promise|any}
   */
  private handleError(error) {
    console.log(error);
    let msg = '请求失败';
    if (error.status == 400) {
      console.log('请求参数正确');
    }
    if (error.status == 404) {
      console.error('请检查路径是否正确');
    }
    if (error.status == 500) {
      console.error('请求的服务器错误');
    }
    console.log(error);
    return {success: false, msg: msg};
  }
}


2、新建登录service类

/**
 * name:登录服务
 * describe:请输入描述
 */
import {Injectable}    from '@angular/core';
import {HttpInterceptorService} from '../utils/HttpUtils.Service'

@Injectable()
export class LoginService {

  constructor(private httpInterceptorService: HttpInterceptorService) {
  }

  /**
   * 登陆功能
   * @param params
   * @returns {Promise<{}>}
   */
  login(username: string, password: string) {
    return this.httpInterceptorService.request({
      method: 'POST',
      url: 'http://localhost:8080/ailschn_community/login/userLogin', // 登录URL
      data: {
        userNickname: username,
        userPassword: password
      },
    });
  }

  /**
   * 注册
   * @param user
   * @returns {any}
   */
  reguster(user: any) {
    return this.httpInterceptorService.request({
      method: 'POST',
      url: 'http://119.232.19.182:8090/reguster',
      data: {
        user: user
      },
    });

  }
}
3、调用登录service

import {Component, OnInit} from '@angular/core';
import {IonicPage, ModalController} from 'ionic-angular';
import {TabsPage} from "../tabs/tabs";
import  {LoginService} from  './login.service';
import {ActivatedRoute, Params} from '@angular/router';
import {Location}     from '@angular/common';
import 'rxjs/add/operator/switchMap';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [LoginService]
})
export class LoginPage implements OnInit {

  private username: string;
  private userpass: string;
  private id: number;

  constructor(public modalCtrl: ModalController, public  loginService: LoginService, public route: ActivatedRoute,
              public location: Location) {
    // http.post()
  }

  ngOnInit() {
    // let id = this.route.params.subscribe(data=>console.log(data.id));
    this.route.params.subscribe((data) => this.id = data.id);
    console.log("路由中传过来的id是:" + this.id);
  }

  back() {
    console.log("点击了返回按钮!")
    this.location.back();
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  /**
   * 登录
   */
  userLogin(username: HTMLInputElement, password: HTMLInputElement, toggle) {

    this.username = username.value;
    this.userpass = password.value;
    this.loginService
      .login(this.username, this.userpass)
      .then(result => {
        console.log("登录接口返回的信息是:" + result);//打印返回的数据
        if (result.code == 200 && result.data) { // 登录成功
          // 在这里做判断,路由跳转
          let modal = this.modalCtrl.create(TabsPage);
          modal.present();
        } else { // 登录失败
          alert(result.message);
        }
      });
  }
}




你可能感兴趣的:(angular4,+,ionic3,http请求封装)