中安拓也のブログ

プログラミングについて書くブログ

【Angular】APIの戻り値の型を型パラメーターとして渡す

以前の記事で書いた、仮想通貨取引所のWeb APIにアクセスした時のコードが冗長だったので、リファクタリングする。

バージョン情報

Angularを使う

  • Angular: 5.2.9

  • Node: 8.1.4

リファクタリング前のコード

RxJSのmapメソッド内で、レスポンスの型をBitflyerTickerModelにキャストしている部分が冗長になってしまっている。

src/app/services/bitflyer.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BitflyerTickerModel } from '../../state/bitflyer-ticker/bitflyer-ticker.model';
import { BitflyerTickerActions } from '../../state/bitflyer-ticker/bitflyer-ticker.action';

const URLS = {
  BASE: 'https://api.bitflyer.jp',
  TICKER: '/v1/getticker'
};

@Injectable()
export class BitflyerService {
  constructor(
    private http: HttpClient,
    private action: BitflyerTickerActions
  ) {}

  getTicker = (): void => {
    // BitflyerTickerModelにキャスト
    this.http
      .get(`${URLS.BASE}${URLS.TICKER}`)
      .map(response => response as BitflyerTickerModel)
      .subscribe(ticker => this.action.setTicker(ticker));
  };
}

リファクタリング後のコード

getメソッドの型パラメーターに、レスポンスの型としてBitflyerTickerModelを指定することによって、mapメソッドとasによるキャストが消え、コードがスッキリした。

src/app/services/bitflyer.service.ts:

// ...上と同じコードなので省略

  getTicker = (): void => {
    // getメソッドの型パラメータでレスポンスの型を指定
    this.http
      .get<BitflyerTickerModel>(`${URLS.BASE}${URLS.TICKER}`)
      .subscribe(ticker => this.action.setTicker(ticker));
  };
}