angular5 httpclient的示例實戰

摘要: 從angular 4.3.0 之後的版本開始使用httpclient,替換了以前的http,引用的包路徑已經變爲了angular/common/http了

一個基礎的 httpclient 樣例javascript

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); } }
相關文章
相關標籤/搜索