dayjournal memo

Total 975 articles!!

Angular #004 – HttpClientModuleでAPI取得

Yasunori Kirimoto's avatar

画像



AngularでHttpClientModuleを利用しAPIを取得するメモ。

  • angular v7.2.0
  • angular Material v7.3.7
  • TypeScript v3.2.2


取得先のAPIとして、今回は下記のような構造の自作した住所検索APIを利用します。

画像



APIを取得するために、まず「Angular CLI」でサービスを作成します。

ng g service service/config

画像



「config.service.ts」と「config.service.spec.ts」が自動作成されたら、下記の赤線のファイルを変更します。


画像



必要なモジュールを追加します。


/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 { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// HTTPサービスインポート
import { HttpClientModule } from '@angular/common/http';
// ボタン・チェックボックス・テーブルモジュールインポート
import {
    MatButtonModule,
    MatCheckboxModule,
    MatTableModule
} from '@angular/material';


@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        // アニメーションモジュールインポート
        BrowserAnimationsModule,
        // ボタン・チェックボックス・テーブルモジュールインポート
        MatButtonModule,
        MatCheckboxModule,
        MatTableModule,
        // HTTPサービスインポート
        HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


API取得先のURLを設定します。


/src/environments/environment.ts

export const environment = {
    production: false,
    apiUrl: 'http://localhost:5000'
};

/src/environments/environment.prod.ts

export const environment = {
    production: true,
    apiUrl: 'http://localhost:5000'
};


サービスにAPIの設定を追加します。


/src/app/service/config.service.ts

import { Injectable } from '@angular/core';

// Observableインポート
import { Observable } from 'rxjs';
// HTTPサービスインポート
import { HttpClient } from '@angular/common/http';
// 設定ファイル読み込み
import { environment } from './../../environments/environment';


@Injectable({
    providedIn: 'root'
})

export class ConfigService {
    constructor(private http: HttpClient) { }

    // API設定
    getAPI(): Observable<any> {
        return this.http.get(environment.apiUrl + '/?address_all=' + '北海道札幌市中央区');
    }
}


取得したAPIをUIに反映します。


/src/app/app.component.ts

import { Component } from '@angular/core';
// API設定インポート
import { ConfigService } from './service/config.service';

let ApiData: string[];

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})


export class AppComponent {
    title = '住所検索API';
    displayedColumns: string[] = ['address_all', 'lat', 'lon', 'level'];
    dataSource = ApiData;

    constructor(private configService: ConfigService) {}

    ngOnInit() {
        // API読み込み
        this.configService.getAPI().subscribe(res => {

            this.dataSource = res;

        });
    }
}

/src/app/app.component.scss

table {
    width: 100%;
}

#mn {
    margin-left: 200px;
    margin-right: 200px;
}

/src/app/app.component.html

<div style="text-align:center">
  <h2>
    {{ title }}
  </h2>
</div>

<div id="mn">
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <!-- 住所カラム -->
    <ng-container matColumnDef="address_all">
      <th mat-header-cell *matHeaderCellDef> 住所 </th>
      <td mat-cell *matCellDef="let element"> {{element.address_all}} </td>
    </ng-container>
    <!-- latカラム -->
    <ng-container matColumnDef="lat">
      <th mat-header-cell *matHeaderCellDef> lat </th>
      <td mat-cell *matCellDef="let element"> {{element.lat}} </td>
    </ng-container>
    <!-- lonカラム -->
    <ng-container matColumnDef="lon">
      <th mat-header-cell *matHeaderCellDef> lon </th>
      <td mat-cell *matCellDef="let element"> {{element.lon}} </td>
    </ng-container>
    <!-- 縮尺レベルカラム -->
    <ng-container matColumnDef="level">
      <th mat-header-cell *matHeaderCellDef> 縮尺レベル </th>
      <td mat-cell *matCellDef="let element"> {{element.level}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>

<router-outlet></router-outlet>


http://localhost:4200」にアクセスし、取得したAPIの値が表示されます。

ng serve --open

画像



book

Q&A