HTTP処理用の汎用サービスを、つくたよー。
現在、Angularでの開発を行っているのですが、汎用的なソースコードってコンテンツとして持っておくと便利だと思うのです。
システムを開発する以上、HTTPのGETメソッドやPOSTメソッドは必ずと言っていいほど使うでしょう。
ということで今回は、HTTP処理用の汎用サービスを作ってみました!
僕のプロフィールはこちら
僕のPC環境
OS:Windows10
Angular:7
汎用HTTPサービス
こんな感じですかね。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor( private http: HttpClient ) { } /** * getメソッドを呼び出す * * @param url URL * @return Observable<Object> */ public get<T>(url: string): Observable<Object> { return this.http.get<T>(url); } /** * postメソッドを呼び出す * * @param url URL * @param param パラメータ * @return Observable<Object> */ public post<T>(url: string, param: any): Observable<Object> { return this.http.post<T>(url, param); } /** * レスポンスハンドリング * * @param status ステータス * @param message メッセージ */ public handleResponse(status: number, message: string): void { console.log(`status:${status}, message:${message}`); } /** * エラーハンドリング * ※想定外エラー * * @param error エラー */ public handleError(error: HttpErrorResponse): void { if (error.error instanceof ErrorEvent) { // A client-side or network error occured. Handle it accordingly. const clientErrorMessage = 'An error occurred:' + error.error.message; console.log(clientErrorMessage); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, const serverErrorMessage = `Backend returned code ${error.status}, body was: ${error.error}`; console.log(serverErrorMessage); } } } @Injectable() export class NoopInterceptor implements HttpInterceptor { constructor() { } public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { let customRequest: HttpRequest<any> = null; customRequest = request.clone({setHeaders: { 'Content-Type': 'application/json' }}); return next.handle(customRequest); } } |
とりあえず、GET・POSTメソッドを用意しました。
メソッドを実行した後のsubscribeなどは呼び出し元で実行する想定です。
また、「Interceptor」もHTTP関連なので、本サービスで定義しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// 共通モジュール import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; // 共通サービス import { HttpService, NoopInterceptor } from './service/http/http.service'; // 共通コンポーネント import { AppComponent } from './app.component'; import { LoginComponent } from './component/login/login.component'; import { TimepickerComponent } from './component/timepicker/timepicker.component'; import { PageNotFoundComponent } from './component/error/page-not-found/page-not-found.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, TimepickerComponent, PageNotFoundComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, NgbModule ], providers: [ HttpService, { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { } |
Interceptorは「app.module.ts」で定義する必要があります。
おすすめ書籍
僕はAngularの勉強をするのに以下の書籍を購入しました。おすすめですよ!
まとめ
ざっくりとHTTPサービスを作成してみました。
こういうサービスは汎用的に使えるので、いっぱい作っていっぱい公開したいですねw
ではまた!