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<R>}
   */
  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<R>|Promise<U>}
   */
  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<R>|Promise<U>}
   */
  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<string>|Promise<T>|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);
        }
      });
  }
}




  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值