LoginSignup
28
32

More than 5 years have passed since last update.

AngularJS でAPIをコールし結果を取得するサンプル②

Last updated at Posted at 2014-04-13

前回の投稿(AngularJSでAPIをコールし結果を取得するサンプル①)に引き続いての投稿です。
APIとの通信は、非同期での通信や応答に時間がかかるAPIなどを考えると、ngResource を利用した方が良いみたいです。

[2014/5/11追記] 続編を書いたのでこちらを参照 ⇒ AngularJSでAPIをコールし非同期で画面を更新する

ngResource を導入する手順

YeomanのAngularJSの雛型(generator-angular)を使う場合

この場合はジェネレータに含まれてるので、そのまま適用すればOK。

スクリーンショット 2014-04-13 21.12.38.png

このあたりを参考に、Yeomanでインストールしてください(⇒Yeoman で AngularJS & UI Bootstrap の開発環境構築

参考

参考:generator-angular (GitHub)

Yeomanを使わず個別にインストールする場合

Bowerでインストール

$ bower install angular-resource --save

index.htmlに追記

index.html
<script src="bower_components/angular-resource/angular-resource.js"></script>

※もしくは $ grunt bower-install を実行すると index.html に記載される。

AngulareJSに組み込み

  • 下記のように ngResource を指定

スクリーンショット 2014-04-13 21.28.36.png

参考

参考:bower-angular-resource (GitHub)

ngResource を利用してAPIアクセスしてみる

①ソースツリーの公開領域に、適当にJSONファイルを用意

app/data/sample.json
[
        {
            "id": "1",
            "name": "山田"
        },
        {
            "id": "2",
            "name": "鈴木"
        },
        {
            "id": "3",
            "name": "高橋"
        }
]

②Factoryに ngResource 経由でJSONファイルにアクセスしリターンするモジュール GetJson を定義

app/scripts/services/api.js
angular.module('apiTestApp')
  .factory('GetJson', function ($resource) {

    var res = $resource('data/sample.json');

    return {
      all: function () {
        return res.query();
      }
    };
  });

③Controllerで先ほどの GetJson を利用しAPIアクセス

app/scripts/controllers/main.js
angular.module('apiTestApp')
  .controller('MainCtrl', function ($scope, GetJson) {

    $scope.items = GetJson.all();

  });

④ViewでHTMLへ表示

app/views/main.html
<div class="container" ng-controller="MainCtrl">
    <table class="table">
        <tr ng-repeat="item in items">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
        </tr>
    </table>
</div>

結果はこんな感じです ⇒ http://hkusu.github.io/AngularJS_apicall_demo2/

ほか

また今回のソース一式はこちらです ⇒ https://github.com/hkusu/AngularJS_apicall_demo2

今回は API経由で全件取得しましたが、ngResource でプロトコルやパラメータの指定もできます。⇒ 公式ドキュメント

WEBサービスを作る場合、データを RestFull な API を利用することはよくあることなので、うまく使いこなしたいなと思います。その場合、Controllerに APIに関する処理を書くとごちゃごちゃしてくるので、今回のように Factory や Service などに切り出しておくとソースがすっきりするのかなと。

28
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
32