首页/Ionic/列表

ionic 发送业务请求HTTP/HTTPS

来源:  2018-04-16 15:47:54    评论:0点击:

    this.httpService.postCheckedHeader(AppConfig.getBaiWangCloudPlatfromDegbugUrl(), xml, this.newUserPwd).subscribe(res => {  
         if (res == null) return;  
         console.log(res)  
       
       }, err => {  
         loader.dismiss();  
         console.log(err);  
       })  

 

    import { Injectable } from '@angular/core';  
    import {  
      Http, Response, Headers, RequestOptions, URLSearchParams, RequestOptionsArgs, RequestMethod  
    } from '@angular/http';  
    import { Observable, TimeoutError } from "rxjs";  
    // import {Utils} from "./Utils";  
    // import {GlobalData} from "./GlobalData";  
    // import {NativeService} from "./NativeService";  
    import { Md5 } from 'ts-md5/dist/md5';  
    import { AppConfig } from "../app/app.config";  
    import { Header } from 'ionic-angular/components/toolbar/toolbar-header';  
      
    @Injectable()  
    export class HttpService {  
      
      constructor(public http: Http  
        // public globalData: GlobalData,  
        // public logger: Logger,  
        // public nativeService: NativeService  
      ) {  
      }  
      
      count: number = 0;  
      
      public request(url: string, options: RequestOptionsArgs): Observable<Response> {  
        this.showLoading();  
        return Observable.create(observer => {  
          this.http.request(url, options).timeout(20000).subscribe(res => {  
            let result = this.requestSuccessHandle(url, options, res);  
            result.success ? observer.next(result.data) : observer.error(result.data);  
          }, err => {  
            observer.error(this.requestFailedHandle(url, options, err));  
          });  
        });  
      }  
      
      
      public get(url: string, paramMap: any = null): Observable<any> {  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Get,  
          search: HttpService.buildURLSearchParams(paramMap)  
        }));  
      }  
      
      
      public postInvoiceCenter(url: string, body: any = {}): Observable<any> {  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Post,  
          body: body,  
          headers: new Headers({  
            'Content-Type': 'text/plain;charset=utf-8',  
            'accept': '*/*',  
          })  
        }));  
      }  
      /**需要鉴权字 */  
      public postCheckedHeader(url: string, body: any, userPwd: string): Observable<any> {  
        var timestamp = (new Date()).valueOf();  
        console.log("previewXML" + body);  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Post,  
          body: body,  
          headers: new Headers({  
            "Content-Type": "text/plain;charset=utf-8",  
            "Access-Control-Allow-Origin": "*",  
            "Access-Control-Allow-Methods": "POST,GET",  
            "timestamp": timestamp,  
            "authorization": Md5.hashStr(body + (userPwd == null ? "" : Md5.hashStr(userPwd)) + timestamp),  
          })  
        }));  
      }  
      /**无需鉴权字,正常调用 */  
      public post(url: string, body: any): Observable<any> {  
        var timestamp = (new Date()).valueOf();  
        console.log("previewXML" + body);  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Post,  
          body: body  
        }));  
      }  
      
      public postFormData(url: string, paramMap: any = null): Observable<any> {  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Post,  
          body: HttpService.buildURLSearchParams(paramMap).toString(),  
          headers: new Headers({  
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'  
          })  
        }));  
      }  
      
      public put(url: string, body: any = {}): Observable<any> {  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Put,  
          body: body  
        }));  
      }  
      
      public delete(url: string, paramMap: any = null): Observable<any> {  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Delete,  
          search: HttpService.buildURLSearchParams(paramMap).toString()  
        }));  
      }  
      
      public patch(url: string, body: any = {}): Observable<any> {  
        return this.request(url, new RequestOptions({  
          method: RequestMethod.Patch,  
          body: body  
        }));  
      }  
      
      
      /**
       * 处理请求成功事件
       */  
      requestSuccessHandle(url: string, options: RequestOptionsArgs, res: Response) {  
        this.hideLoading();  
        console.log("responseXML:" + res["_body"]);  
        return { success: true, data: res["_body"] };  
      
      }  
      
      
      /**
       * 处理请求失败事件
       */  
      private requestFailedHandle(url: string, options: RequestOptionsArgs, err: Response) {  
        //IS_DEBUG && console.log('%c 请求失败 %c', 'color:red', '', 'url', url, 'options', options, 'err', err);  
        this.hideLoading();  
        // if (!this.nativeService.isConnecting()) {  
        //   this.nativeService.alert('请连接网络');  
        // } else if (err instanceof TimeoutError) {  
        //   this.nativeService.alert('请求超时,请稍后再试!');  
        // } else {  
        let status = err.status;  
        let msg = '请求发生异常';  
        if (status === 0) {  
          msg = '请求失败,请求响应出错';  
        } else if (status === 404) {  
          msg = '请求失败,未找到请求地址';  
        } else if (status === 500) {  
          msg = '请求失败,服务器出错,请稍后再试';  
        }  
        // this.nativeService.alert(msg);  
        // this.logger.httpLog(err, msg, {  
        //   url: url,  
        //   status: status  
        // });  
        //}  
        return err;  
      }  
      
      /**
       * 将对象转为查询参数
       */  
      private static buildURLSearchParams(paramMap): URLSearchParams {  
        let params = new URLSearchParams();  
        if (!paramMap) {  
          return params;  
        }  
        for (let key in paramMap) {  
          let val = paramMap[key];  
          if (val instanceof Date) {  
            //val = Utils.dateFormat(val, 'yyyy-MM-dd hh:mm:ss')  
          }  
          params.set(key, val);  
        }  
        return params;  
      }  
      
      /**
       * 格式化url使用默认API地址:APP_SERVE_URL
       */  
      // private formatUrlDefaultApi(url: string = ''): string {  
      //   return Utils.formatUrl(url.startsWith('http') ? url : APP_SERVE_URL + url)  
      // }  
      
      /**
       * 给请求头添加权限认证token
       */  
      private addAuthorizationHeader(options: RequestOptionsArgs): RequestOptionsArgs {  
        // let token = this.globalData.token;  
        // if (options.headers) {  
        //   options.headers.append('Authorization', 'Bearer ' + token);  
        // } else {  
        //   options.headers = new Headers({  
        //     'Authorization': 'Bearer ' + token  
        //   });  
        // }  
        return options;  
      }  
      
      private showLoading() {  
        if (++this.count === 1) {//一旦有请求就弹出loading  
          //this.globalData.showLoading && this.nativeService.showLoading();  
        }  
      }  
      
      private hideLoading() {  
        if (--this.count === 0) {//当正在请求数为0,关闭loading  
          // this.nativeService.hideLoading();  
          // this.globalData.showLoading = true;  
        }  
      }  
    }





来源:https://blog.csdn.net/merrylilili/article/details/79138826
为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权