您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)angular8封裝http服務(wù)的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
要在angular里使用http服務(wù)必須先在
app.module.ts
里導入HttpClientModule
模塊,不然會報錯。
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; // 導入關(guān)鍵模塊 import { HttpClientModule } from '@angular/common/http'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule { }
根據(jù)angular的官網(wǎng),請求返回的是數(shù)據(jù)的
Observable
對象,所以組件要訂閱(subscribe) 該方法的返回值。
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class HttpService { private http: any; constructor(private Http: HttpClient) { this.http = Http; } // get方法 public get(url: string, options?: Object, params?: Object): Observable<{}> { let httpParams = new HttpParams(); if (params) { for (const key in params) { if (params[key] === false || params[key]) { httpParams = httpParams.set(key, params[key]); } } } return this.http.get(url, { headers: options, params: httpParams }).pipe(catchError(this.handleError)); } // post方法 public post(url: string, body: any = null, options?: Object): Observable<{}> { return this.http.post(url, body, options).pipe(catchError(this.handleError)); } // post表單 public postForm(url: string, body: any = null, options?: Object): Observable<{}> { let httpParams = new HttpParams(); if (body) { for (const key in body) { if (body[key] === false || body[key]) { httpParams = httpParams.set(key, body[key]); } } } return this.http.post(url, httpParams, options).pipe(catchError(this.handleError)); } /** * 處理請求失敗的錯誤 * @param error HttpErrorResponse */ private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { console.error('An error occurred:', error.error.message); } else { console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } console.log(error); return throwError(error.error); } }
這里貼上get、post
兩種的方式的例子,其他如delete這些就不展示了,一樣的原理。
稍微說一下里面的細節(jié):
return this.http.post(url, httpParams, options).pipe(catchError(this.handleError));
這里返回的是Observable<{}>
,并通過pipe管道處理請求異常,異常的處理在最下面的handleError
方法里。
// 引入封裝好的http服務(wù) constructor(private http: HttpService) { } /** * 測試get方法 * @param successCallback 成功的回調(diào) * @param failCallback 失敗的回調(diào) */ public testGet(url: string, successCallback?: Function, failCallback?: Function) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=UTF-8' }) }; this.http.get(url, httpOptions.headers).subscribe( (res: any) => { successCallback(res); // 成功走sucessCallback }, (err: HttpErrorResponse) => { failCallback(err); // 失敗 } ); }
這是一個具體的get請求service,testGet
定義里三個參數(shù),一個是請求地址,還有成功的回調(diào)與失敗的回掉。
subscribe訂閱observable 對象。
在component里使用
this.testService.testGet('url', (res:any) => {}, (err:any) =>{});
關(guān)于“angular8封裝http服務(wù)的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。