LoginSignup
31
33

More than 5 years have passed since last update.

Angularのng-resourceの使い方

Posted at

What is ?

Angularの$httpをラッピングしていて、サーバとのHTTP通信を行え、RESTfullにやり取りを行うためのサービス。

Version

AngularJS 1.4.8 で動作確認

Install

bower.json
"angular-resource": "1.4.8"

How to

まずは、登録

app.js
sampleApp = angular.module('sampleApp', ['ngResource']);

次にAPI通信するモジュールをFactoryとして作成
※例としてUserモデルに関するAPIを実行するモジュールとします

User.js
sampleApp.factory('User', ['$resource', function($resource) {

  // 「get」「find」「create」の3つのアクションを定義
  return $resource(
    'http://sample.com/api/users/:id',
    {id: '@id'},
    {
      get: {method: 'GET', isArray: true}, // apiの戻り値が配列の場合は「isArray: true」を指定する
      find: {method: 'GET'},
      create: {method: 'POST'}
    }
  );
}]);
  • $resource
    • 第一引数
      • URLを指定する。
      • 「:id」のような形式でURLパラメータを指定できる
    • 第二引数
      • デフォルトパラメータを指定する
      • 上記の例では、メソッド呼び出し時のパラメータのキーに「id」があればそれをURLパラメータに埋め込んでくれる
    • 第三引数
      • アクションの定義
      • 各アクション毎に「method」等のオプションを設定できる。設定可能なオプションについては公式ドキュメントを参照

最後にコントローラーでの実行例

SampleController.js
sampleApp.controller('SampleController', ['User', function(User) {
  self = this;

  // GET http://sample.com/api/users
  User.get().$promise.then(function(users) {
    self.users = users;
  }).catch(function(data, status) {
    alert('error');
  });

  // GET http://sample.com/api/users/1
  User.find({id: 1}).$promise.then(function(user) {
    self.user = user;
  }).catch(function(data, status) {
    alert('error');
  });

  // POST http://sample.com/api/users {name: "test", address: "test@sample.com"}
  var user = new User({name: 'test'}); // パラメータを引数で指定できる
  user.address = 'test@sample.com'; // newした後にパラメータを付与することも可能
  // GETメソッド以外のアクションを実行するときはprefixに「$」をつける
  // またアクションの戻り値がpromiseになっている
  user.$create().then(function(data) {
    console.log(data);
  }).catch(function(data, status) {
    alert('error');
  });

}]):

Interceptor

Interceptorを登録することで、共通のヘッダー処理や共通のエラーハンドリングを行うことができる。

app.js
sampleApp.config(['$httpProvider'], function($httpProvider) {
  $httpProvider.interceptors.push(['$q', function($q) {
    return {
      // リクエストの前処理
      request: function(config) {
        console.log(config);
        return config;
      },
      // レスポンス受信時の前処理
      response: function(response) {
        console.log(response);
        return response;
      },
      // 通信エラー時の処理
      responseError: function(rejection) {
        console.log(rejection);
        return $q.reject(rejection);
      }
    };
  }]);
});
31
33
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
31
33