2016-07-20 12 views
0

私のアプリケーションでは、ユーザーが複数のレコードを追加できるフォームがあります。ページがロードされると、既存のレコードをDBでチェックするためにGETリクエストを行う必要があります。存在するレコードがある場合は、そのレコードをページに挿入します。問題はない。

問題は、DBに既存のレコードがない場合、サーバーはNo 204 Contentを返します。コントローラでは、success関数はまだ実行されますが、$ promiseオブジェクトと$ resolved:trueだけのデータはありません。

工場:ここ

はコードである

return $resource (
     https://my.backend/api/records/:id", 
     {}, 
     { 
      "getExistingRecords": { 
       method: 'GET', 
       isArray: false, 
       params: {id: '@id'}, 
       withCredentials: true} 
     } 
    ) 

コントローラー:

function initialize(id){ 
      alertFactory.getExistingRecords({id: id}) 
       .$promise 
       .then(function (records){ 
        if(records){ 
         $scope.existingRecords = records; 
        }else { 
         $scope.existingRecords = {}; 
        } 
       },function(error){ 
        Notification.error(error); 
       }); 
     } 
initialize(id); 

サーバが返す "204はコンテンツがなく、" 私は、コンソールからこれを取得しない場合は

Console Image

これを処理してレコードオブジェクトのオブジェクトプロパティをチェックする唯一の方法はありますか?

たとえば

function initialize(id){ 
      alertFactory.getExistingRecords({id: id}) 
       .$promise 
       .then(function (records){ 
        if(records.recordName){ 
         $scope.existingRecords = records; 
        }else { 
         $scope.existingRecords = {}; 
        } 
       },function(error){ 
        Notification.error(error); 
       }); 
     } 
initialize(id); 

または私は他の何かが足りないのですか?

+0

は 'あなたの$リソース定義で' true'になりisArray'ないでしょうか?応答が空の場合、サーバーは '204 no content'の代わりに空の配列を返すことができます。少なくともgetExistingRecords()アクションの名前は、配列でなければならないことを示唆しています。 –

+0

レコードが存在していて長さが0より大きいかどうかを常にチェックすることができます... – theDarse

答えて

0

レスポンスでステータスコードを取得できる方が良いでしょう。そのための直接的な方法はありません。しかし、あなたはインターセプタとworkaroundことができます。

var resource = $resource(url, {}, { 
    get: { 
     method: 'GET' 
     interceptor: { 
      response: function(response) {  
       var result = response.resource;   
       result.$status = response.status; 
       return result; 
      } 
     } 
    }        
}); 

そして今、次のことができます。

   if(records.$status === 200){ 
        $scope.existingRecords = records; 
       }else { 
        $scope.existingRecords = {}; 
       } 
+0

ありがとう! – conbra

関連する問題