当前位置:首页 >> 网络编程

基于angular2 的 http服务封装的实例代码

最近在项目中折腾了下angular2,所以出来跟大家分享,希望有帮助,每个公司业务不一样,按实际情况而定,个人学习心得,不作为标准。

1、定义http-interceptor.service.ts服务,统一处理http请求

/**
 * name:http服务
 * describe:对http请求做统一处理
 * author:Angular那些事 
 * date:2017/6/3
 * time:11:29
 */
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 {
 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"];
 if (body) {
  return {
  data: res.json().content || {},
  page: res.json().page || {},
  statusText: res.statusText,
  status: res.status,
  success: true
  }
 }
 else {
  return {
  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,service定义此模块的所有http数据请求,我这里演示登录模块:login.service.ts

/**
 * name:登录服务
 * describe:请输入描述
 * author:Angular那些事
 * date:2017/6/1
 * time:00:13
 */
import {Injectable}    from '@angular/core';

import {HttpInterceptorService} from 'app/commons/service/http-interceptor.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://119.232.19.182:8090/login',
  data: {
  loginName: userName,
  password: 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、在component注入servicelogin.service.ts。调用seriveLogin.service.ts服务定义的方法,这里通过login.component.ts演示

/**
 * name:登录组件
 * describe:请输入描述
 * author:Angular那些事
 * date:2017/6/1
 * time:00:30
 */
import {Component} from '@angular/core'
import {LoginService} from './login.service'

@Component({
 selector: 'login',
 templateUrl: './login.component.html',
 providers: [LoginService],
})

export class LoginComponent {
 private userName: string;
 private passWord: string;

 constructor(private loginService: LoginService) {
 }

 /**
 * 登录
 */
 toLogin() {
 this.loginService.login(this.userName, this.passWord).then(result => {
  console.log(result);//打印返回的数据
 });
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。