這篇文章主要介紹了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); } }
上面是我整理給大家的,希望未來會對大家有幫助。
相關文章:
#以上是angular5 httpclient的範例實戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!