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); } }
相关推荐
84487600 2020-08-16
似水流年梦 2020-08-09
knightwatch 2020-07-26
fengchao000 2020-06-16
标题无所谓 2020-06-14
sicceer 2020-06-12
yanghui0 2020-06-09
yanghui0 2020-06-09
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。
wanghongsha 2020-06-04
jiaguoquan00 2020-05-26
zhaolisha 2020-05-16
wanghongsha 2020-05-05
wanghongsha 2020-04-14
knightwatch 2020-04-11
hygbuaa 2020-03-27
zergxixi 2020-03-24