首頁  >  文章  >  web前端  >  angular8如何封裝http服務

angular8如何封裝http服務

青灯夜游
青灯夜游轉載
2021-03-12 09:44:062322瀏覽

本篇文章為大家介紹一下angular8封裝http服務的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

angular8如何封裝http服務

相關推薦:《angular教學

HttpClientModule

要在angular裡使用http服務必須先在app.module.ts裡導入HttpClientModule模組,不然會報錯。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
// 导入关键模块
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 { }

封裝http

根據angular的官網,請求返回的是資料的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這些就不展示了,一樣的原理。

細節

稍微說一下裡面的細節:

return this.http.post(url, httpParams, options ).pipe(catchError(this.handleError));

這裡回傳的是Observable<{}> ,並透過pipe管道處理請求異常,異常的處理在最下面的handleError 方法裡。

使用

// 引入封装好的http服务
constructor(private http: HttpService) { }

/**
   * 测试get方法
   * @param successCallback 成功的回调
   * @param failCallback 失败的回调
   */
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定義里三個參數,一個是請求位址,還有成功的回調與失敗的回掉。
subscribe訂閱observable 物件。

在component裡使用

this.testService.testGet('url', (res:any) => {}, (err:any) =&gt ;{});

總結

angular封裝http請求並不難,官網也講得比較清楚。

個人認為最重要的還是這種封裝服務的思想,而angular為什麼要區別元件服務?

一個重要的原因就是它希望,資料展示邏輯資料存取邏輯 是分拆開的,元件需要在頁面上展示的資料就委託為某個服務去取!以此使程式碼得到高復用。

更多程式相關知識,請造訪:程式設計影片! !

以上是angular8如何封裝http服務的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除