2016-11-23 13 views
2

私はこのコードをサービスに持っています。私の知る限り、$http.get()は約束を返し、約束は非同期に実行されるため、私のサービスでデータを返すのになぜdeffered.resolve(res.data)を使用する必要がありますか?どうもありがとう。

data.posts = function(page, perPage, format, orderBy) { 
     var deffered = $q.defer(); 
     $http.get(hostName, { 
      params: { 
       'page': page, 
       'per_page': perPage, 
       'filter[post_format]=': format, 
       'filter[orderby]=': orderBy, 
       'order': 'desc' 
      } 
     }).then(function(res) { 
      deffered.resolve(res.data); 
     }) 
     return deffered.promise; 
    } 
+0

DONTはそれを使用するをお読みください。 XHR GETにエラーがある場合、延期された約束はハングします。 – georgeawg

答えて

0

真にサービス中の場合、遅延は必要ありません。サービスのメソッドは、上記の$ http要求から約束を返します。

function exampleService($http) { 
    var data = this; 
    data.post = function(page, perPage, format, orderBy) { 
     return $http.get(hostName, { 
      params: { 
      'page': page, 
      'per_page': perPage, 
      'filter[post_format]=': format, 
      'filter[orderby]=': orderBy, 
      'order': 'desc' 
      } 
     }).then(function(res) { 
      //do stuff with success 
     }) 
     .catch(function(err) { 
      //do stuff with error 
     }) 
     .finally(function() { 
      //optionally use this as well maybe if you had loading type overlay/icon 
     }); 
    }; 
    } 
    //preferred method as it makes methods available before the sevice has been returned 

function exampleService($http) { 
    function post(page, perPage, format, orderBy) { 
     return $http.get(hostName, { 
      params: { 
      'page': page, 
      'per_page': perPage, 
      'filter[post_format]=': format, 
      'filter[orderby]=': orderBy, 
      'order': 'desc' 
      } 
     }).then(function(res) { 
      //do stuff with success 
     }) 
     .catch(function(err) { 
      //do stuff with error 
     }) 
     .finally(function() { 
      //optionally use this as well maybe if you had loading type overlay/icon 
     }); 
    } 
    //revealing module pattern 
    return { 
    post: post, 

    }; 
} 
0

なぜそれを使うのか?作者はよく分からなかったので。しかし、many reasons not to use itがあります。

コードが

data.posts = function(page, perPage, format, orderBy) { 
    return $http.get(hostName, { 
     params: { 
      'page': page, 
      'per_page': perPage, 
      'filter[post_format]=': format, 
      'filter[orderby]=': orderBy, 
      'order': 'desc' 
     } 
    }).then(function(res) { 
     return res.data; 
    }); 
};