zoukankan      html  css  js  c++  java
  • angular5 httpclient的示例实战

    摘要: 从angular 4.3.0 以后的版本开始使用httpclient,替换了之前的http,引用的包路径已经变为了angular/common/http了

    一个基础的 httpclient 样例

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpResponse } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    import { HttpDefaultOptions } from './http.default.options';
    
    @Injectable()
    export class Service {
    
      private static METHOD_DELTE = 'DELETE';
      private static METHOD_POST = 'POST';
      private static METHOD_GET = 'GET';
      private static METHOD_PUT = 'PUT';
    
      constructor(private httpClient: HttpClient) {
      }
    
      /**
       * 将数据上传
       * @param data
       * @param {Function} func
       */
      uploadDataPost(data: any, func: Function) {
        let url = '/api/test';
        this.apiPost(url, data)
          .subscribe((response: HttpResponse) => {
            func(response);
          }, error => {
            func(undefined);
          });
      }
    
      /**
       * 返回json 格式的obj 对象
       * @param url
       * @param body
       * @param urlSearchParams
       * @returns {Observable<{}>}
       */
      apiPost(url, body, urlSearchParams?: any): Observable<{}> {
        let options = {
          body: body ? body : null,
          params: urlSearchParams,
          responseType: 'json'
        };
        return this.httpClient.request(Service.METHOD_POST, url, options);
      }
    
      /**
       * 返回一个obj 对象
       * @param url
       * @param urlSearchParams url 的查询参数
       * @returns {Observable<{}>}
       */
      apiGet(url, urlSearchParams?: any): Observable<{}> {
        let options = {
          params: urlSearchParams,
          responseType: 'json'
        };
        return this.httpClient.request(Service.METHOD_GET, url, options);
      }
    
    }
  • 相关阅读:
    iPhone 调用Web Service 例子(转)
    iPhone开发:在UIAlertView中显示进度条(转)
    Oracel 分页
    NYOJ 477
    NYOJ 108(数组中存的是前n个数的和)
    NYOJ 199
    NYOJ 311(完全背包)
    高效斐数(前92位)
    NYOJ 57(6174问题)
    NYOJ 546(分珠宝)
  • 原文地址:https://www.cnblogs.com/itrena/p/9134841.html
Copyright © 2011-2022 走看看