らいふうっどの閑話休題

興味のあることをゆる~く書いていく

How to Create a Service with HttpClient and Injectable in Angular 9/8 の翻訳

mediumHow to Create a Service with HttpClient and Injectable in Angular 9/8 の翻訳です。

このチュートリアルでは、 HttpClient を使用して、 Angular アプリケーションを REST API サーバーに接続するためのサービスを構築する方法を学習します。

Angular サービスを実装して、REST API サーバーからのデータの取得を処理するコードをカプセル化する方法について説明します。

f:id:ic_lifewood:20200102001855p:plain

Angular サービスは、Angular 依存関係インジェクターを使用して他のサービスまたはコンポーネントに挿入できる単なる TypeScript クラスです。

前提条件

Node 、NPM 、Angular CLI が必要で、Angularプロジェクトを初期化する必要があります。

ステップ1 — HttpClient モジュールのインポート

src/app/app.module.ts ファイルを開き、次のように更新します。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

ステップ2 — Angular Service の作成

新しいターミナルを開き、次のコマンドを実行します。

$ ng generate service backend

ステップ3 — HttpClient のインポートと注入

src/app/backend.service.ts ファイルを開き、次のように HttpClient をインポートして注入します。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BackendService {
  constructor(private httpClient: HttpClient) { }
}

HttpClient をインポートし、サービスの constructor を介して注入します。

ステップ4 — HTTPリクエストを送信するメソッドの定義

次に、データを取得するためにサーバーにGETリクエストを送信する get() メソッドを定義します。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  constructor(private httpClient: HttpClient) { }

  public get(){
    return this.httpClient.get("http://server.com/endpoint");
  }
}

HttpClientget() メソッドを呼び出して、GET 要求を REST API サーバーに送信します。

ステップ5 — Angular コンポーネントの作成

端末に戻り、次のコマンドを実行してhomeという名前のコンポーネントを生成します。

$ ng generate component home

ステップ6 — Angular Service の注入

src/app/home/home.component.ts ファイルに移動し、次のようにバックエンドサービスをインポートして注入します。

import { Component, OnInit } from '@angular/core';
import { BackendService } from '../backend.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  data= [];

  constructor(private backendService: BackendService) { }

}

ステップ7 — サービスメソッドの呼び出し

最後に、次のように、サービスの get() メソッドを呼び出して GET リクエストを送信できます。

  ngOnInit() {
    this.backendService.get().subscribe((ret: any[])=>{
      console.log(ret);
      this.data = ret;
    })  
  }

ステップ8 — ngFor を使用したデータの表示

<div>
  <ul>
    <li *ngFor="let item of data">
      {{item.name}}
    </li>
  </ul>
</div>

ここでは、データ要素に名前属性があると仮定します。

他の Angular チュートリアル をご覧ください。

個人の Web サイトである TwitterLinkedIn 、および Github を介して著者に連絡するか、著者をフォローできます。

まとめ

この投稿では、 Angular でサービスを作成し、 HttpClient を使用して HTTP リクエストを REST API バックエンドに送信し、 ngFor ディレクティブを使用して API から返されたデータを最終的に表示する方法を説明しました。

itnext.io

itnext.io