Angular2でHTTPでサーバーからJSONデータ取得

Angular2のHTTPクライアントを使って、サーバーからGetリクエストでJSONファイルのデータを取得するサンプルを作成しました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)

※目次をクリックすると目次の下部にコンテンツが表示されます。

Angular2のHTTPクライアントを使ってサーバーからJSONデータ取得
1)ライブラリ、サービスのインポート
 
①httpライブラリをインポート
 
Coreには含まれていないため、メインのHTMLファイルに以下の記述追加。
 
<script src=”https://code.angularjs.org/2.0.0-beta.17/http.dev.js”></script>
 
②メインのコンポーネントで’rxjs/Rx’、HTTP、HttpModule、Observableをインポート。 
import ‘rxjs/Rx’;
import {HttpModule} from ‘@angular/http’;
import {Http} from ‘@angular/http’;
import {Observable} from ‘rxjs/Observable’;
 
‘rxjs/Rx’は、HTTPのgetなどのリターンがObservableで、このObservableを操作するのに必要。
 
③@NgModuleでHttpModuleをインポート
 
@NgModule({
 imports: [
  BrowserModule,
  HttpModule
 ],
 
④コンポーネントクラスのconstructorに”HTTP”を指定
 
constructor (private _http: Http) {}
 
2)HTTPクライアントのHTTP Getでデータ取得
 

this._http.get(url)
          .subscribe(
            res  => {
              this.friends = res.json();
              this.status = res.status;
              this.error = "";
            },
            error => {
              this.error = error.text().substr(287,100);
              this.status = error.status;
              this.friends = [];
            },);

 
・HTTP GetからのリターンはPromiseではなく、”RxJS”ライブラリのObservableがリターンされる。”RxJS”ライブラリのObservableを使用する事によって非同期処理を行うことができ、Promiseより多様な処理を行うことができる。
※RxJS (“Reactive Extensions”)ライブラリ
※ObservableをPromiseに変換する方法はこちら
 
・レスポンスオブジェクトを直接利用できる形式になっていないので、json()メソッドを使って、サーバーからのリターンデータをJSONオブジェクトに変換する。

デモ
Angular : 4.4.3(2.0.0でも動作確認済み)
Bootstrap : 3.x

Loading…

<html>
  <head>
    <title>Angular 2 Demo</title>
    <script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
    <script src="https://npmcdn.com/systemjs@0.19.39/dist/system.src.js"></script>
    <script src="./js/systemjs.config.js"></script>
    <script>
      System.import('./ts/app.ts').catch(function(err){ console.error(err);  });    </script>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/styles.css">
  </head>
  <body>
    <div class="container">
      <my-app>Loading...</my-app>
    </div>
  </body>
</html>

(systemjs.config.js)
(function (global) {
  var ngVer = '@4.4.3';
  System.config({
    transpiler: 'ts',
    typescriptOptions: {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true,
      "strict": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      'npm:': 'https://unpkg.com/'
    },
    map: {
      'app': 'app',
      '@angular/animations': 'npm:@angular/animations' + ngVer + '/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations' + ngVer + '/bundles/animations-browser.umd.js',
      '@angular/core': 'npm:@angular/core' + ngVer + '/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common' + ngVer + '/bundles/common.umd.js',
      '@angular/common/http': 'npm:@angular/common' + ngVer + '/bundles/common-http.umd.js',
      '@angular/compiler': 'npm:@angular/compiler' + ngVer + '/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser-animations.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + ngVer + '/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http' + ngVer + '/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router' + ngVer + '/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router' + ngVer + '/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms' + ngVer + '/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs@5.0.1',
      'tslib':                     'npm:tslib/tslib.js',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.3.2/lib/typescript.js',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts',
        meta: {
          './*.ts': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });

})(this);

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { Component } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Http } from '@angular/http';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Observable';

interface Friend {
  id: number,
  name: string,
  age: number,
  address: string
}

@Component({
  selector: 'my-app',
  template: `
    <button (click)="getFriends(true)">データ取得</button>
    <button (click)="getFriends(false)">データ取得(エラー)</button><br />
    <div *ngIf="status">
      <strong>レスポンスデータ</strong><br />
      <table class="table table-striped">
        <thead><tr>
          <th>№</th><th>名前</th><th>年齢</th><th>住所</th>
        </tr></thead>
        <tbody>
          <tr *ngFor="let item of friends">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>{{item.address}}</td>
          </tr>
        </tbody>
      </table>
      ステータス:{{status}}<br />
      エラー:{{error}}<br />
    </div>
  `
})
export class AppComponent {
  public status;
  public error;
  constructor (private _http: Http) {}
  private _heroesUrl = '/json/friends.json';
  public friends:Friend[];
  getFriends(tf: boolean) {
    var url = (tf ? this._heroesUrl : "invalid-url");
    this._http.get(url)
              .subscribe(
                res  => {
                  this.friends = res.json();
                  this.status = res.status;
                  this.error = "";
                },
                error => {
                  this.error = error.text().substr(287,100);
                  this.status = error.status;
                  this.friends = [];
                },);
  }
}

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

platformBrowserDynamic().bootstrapModule(AppModule);

関連記事の目次

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください