中安拓也のブログ

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

AngularでRxJSの練習 #2 - APIを叩く

前回の記事に引き続きRxJSの簡単なデモを作成していきます。

開発環境

  • Angular: 5.2.3

  • rxjs: 5.5.2

  • Typescript: 2.4.2

  • OS: darwin x64

  • Node: 8.1.4

練習3: GitHub APIを叩く

GitHub APIからユーザーの一覧(30人分)を取得した後、先頭のユーザー3人分だけを出力するということをやります。

AppModuleの設定

APIのアクセスには、AngularのHttpモジュールを使用するため、前準備として、app.module.tsの設定を変更します。importsHttpModuleを追加してください。

src/app/app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// rxjsのオペレーターを一括import
import 'rxjs/Rx';
import { HttpModule } from '@angular/http'; // <- add this!

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule, // <- add this!
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

RxJSでAPI呼び出し

続いて、APIを呼び出すソースコードについて説明します。 flatMapがキモになっていて、Array(30)のObservable 1件をflatMapで30件のObservableに分解して、 先頭の3件のみを取得できるようにしています。

src/app/app.component.ts:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Request, RequestMethod } from '@angular/http';

@Component({
  selector: 'app-root',
  template: ``,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private http: Http) {}

  ngOnInit() {
    this.http.get(`https://api.github.com/users`)
      .map(res => res.json())
      .flatMap(observable => observable) // 1つのObservableを30件のObservableに分解する
      .take(3) // 先頭の3件だけ取得
      .subscribe(console.log);
  }
}

実行結果

練習3で書いたソースコードを実行すると👇のように表示されます。 f:id:l08084:20180303103726p:plain

参考サイト

ninjinkun.hatenablog.com