LoginSignup
13
12

More than 5 years have passed since last update.

AngularJSで上手に複数の$resourceの結果を受け取りたい

Last updated at Posted at 2014-12-26

AngularJSで上手に複数の$resourceの結果を受け取りたい

画面に詳細情報とプルダウン項目を表示するような画面があって、このような情報を取ってくるサービスがあった場合、

angular.module('app')
  .factory('service', ['$resource', function ($resource) {
    return {
      /** DBからプルダウン項目の内容を取得 */
      item: $resource('/api/item/:key', {key: '@key'}),
      /** DBから詳細情報を取得 */
      detail: $resource('/api/detail/:detailId', {key: '@detailId'})
    };
  }]);

$q.all()を使うことで複数のPromiseを待つことができます。

$q.all([service.detail.get({detailId: $routeParams.detailId}).$promise,
        service.item.get({key: '00001'}).$promise,
        service.item.get({key: '00002'}).$promise])
  .then(function (result) {
    // 詳細情報
    $scope.detail = result[0];
    // 申請可否(プルダウン)
    $scope.okngList = result[1];
    // 可否理由(プルダウン)
    $scope.applyReasonList = result[2];

    $scope.loading = false;
  });

thenに渡すfunctionの引数に$q.all()に渡したpromiseの結果が入ってくるので、取り出すだけです。非常に便利です。


参考

https://docs.angularjs.org/api/ng/service/$q
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise

13
12
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
13
12