AngularJSの$resourceを使ったのでメモ

$resourceオブジェクトを使って調べた事メモ

 

公式ドキュメントを順に見て行くと

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

空の参照が返って処理が終わるとデータが詰められる?これ分かると便利な機能!!

とりあえずこの件はおいといてwドキュメントを読み進めると

  • HTTP GET "class" actions: Resource.action([parameters], [success], [error])
  • non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
  • non-GET instance actions: instance.$action([parameters], [success], [error])

 

Success callback is called with (value, responseHeaders) arguments. Error callback is called with (httpResponse) argument.

$httpの様にコールバックを登録してレスポンスを受けれるとのこと

取り方はこんな感じ

var Book = $resource('http://xxx.com/webapi/v1/books/:book_id');
Book.get({book_id : 0000},
    function (value, responseHeaders) {
      $scope.book = value;
    },
    function (httpResponse) {
        /* error */
    }

もう一つのコールバックでの取り方はpromiseを使う方法

The Resource instances and collection have these additional properties:

  • $promise: thepromiseof the original server interaction that created this instance or collection.

 っで、空の参照の件に戻って、まずはサンプル

var Book = $resource('http://xxx.com/webapi/v1/books/:book_id');
$scope.book = Book.get({book_id : 0000});

これでおしまいw

ここが$resourceの良いところで、悩んだところ。

get()の戻りで値を確認するとResourceオブジェクトが返ってきてるだけで、値なんて入ってない!

$resourceのコード見ても

          var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
              中略
          if (!isInstanceCall) {
            // we are creating instance / collection
            // - set the initial promise
            // - return the instance / collection
            value.$promise = promise;
            value.$resolved = false;

            return value;
          }

だけど実行すると$scope.bookが更新されてviewに反映される

値見ても確かに反映されてる。。。

っで、もう一度$resourceのコード見ると

shallowClearAndCopy(data, value);

これだっーーーってことで、内部の$httpのpromiseで値詰めてました

ってことで、$resourceはpromiseとfutureオブジェクトを提供してくれるので、$scopeのデータバインディングが利用できるならfutureオブジェクトを利用するのが良いのかなって結論でした