温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

angular5 httpclient的示例实战

发布时间:2020-08-24 14:06:33 来源:脚本之家 阅读:155 作者:今天来找bug 栏目:web开发

从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);
 }
}

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI