2017-11-07 2 views
0

私はいくつかのデータを返すWebサービスを持っています。私は角度サービスへのHTTPリクエストの呼び出しを移動したいコードの重複を防ぐために:、別の値で角度約束を作成する

angular.module('abc', []) 
    .factory('def', function() { 
     return { 
      getData: function() { 
       return $http.post('/path/', {}); 
      } 
     }; 
    }); 

すべてが良いですが、必要なデータが内部のオブジェクトを複雑にしていると私は毎回書く必要があります:

def.getData().then(function (response) { 
    scope.obj = response.data.qwe.rty.xyz; 
}); 

を何約束を返す最も簡単な方法はresponse.data.qwe.rty.xyzの値をsuccessCallbackに直接送りますか?あなたがthen()を呼び出した上で約束を返し$http.post('/path/', {})

def.getData().then(function (obj) { 
    scope.obj = obj; 
}); 

答えて

4

コール:そして、私はこのように書くことができます。 then()も約束を返すので、コールをチェーンすることができます。あなたのコードは、したがって、このようになります。

angular.module('abc', []) 
    .factory('def', function() { 
     return { 
      getData: function() { 
       return $http.post('/path/', {}) 
         .then(function(response) { 
          return response.data.qwe.rty.xyz; 
         }); 
      } 
     }; 
    }); 
2

あなたがそうのよう$qプロバイダに

を実装延期動作使用することができます。

angular.module('abc', []) 
.factory('def', function ($q) { 

    return { 
     getData: function() { 
      var def = $q.defer 
      $http.post('/path/', {}).then(function(response){ 
       def.resolve(response.data.qwe.rty.xyz) 
      }); 
      return def.promise; 
     } 
    }; 
}); 

と同様に、あなたのコントローラでそれを使用します。

def.getData().then(function (response) { 
scope.obj = response; 
}); 
関連する問題