angular中的http请求封装

前端之家收集整理的这篇文章主要介绍了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 || {},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};
  }
}

@H_404_5@

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);
        }
      });
  }
}
原文链接:https://www.f2er.com/angularjs/146412.html

猜你在找的Angularjs相关文章