2014-10-18 38 views
1

我想为我的http请求创建缓存,所以我想复制$ http回调。

这是我的函数:

function getData() { 
    if(cacheExists()) { 
     return cache; 
    } 

    return $http({ 
      method: 'POST', 
      url: 'http://something.com', 
      params: {something} 
     }); 
} 

,这是我如何处理它:

getData() 
     .success(function(data) { 
      $scope.spot = data.data; 
      console.log($scope.spot); 
     }).error(function(data) { 
      console.log('error'); 
     }); 

这将angularjs $ HTTP方法, 完美地工作,但不会有我的“缓存工作“,因为”缓存“应该有这些回调:成功&错误,我该如何创建它们?

回答

4

它是因为$ http返回一个承诺。您可以使用$ q服务解决此问题,并将缓存作为承诺返回。

//inject $q 
function getData() { 
    var deffered = $q.defer() 
    if(cacheExists()) { 
     deffered.resolve(cache); 
    } else { 
     $http({ 
      method: 'POST', 
      url: 'http://something.com', 
      params: {something} 
     }) 
     .success(function(data) { 
     deffered.resolve(data); 
     }) 
     .error(function(response) { 
     deffered.reject(response); 
     }) 
    } 

    return deffered.promise; 
} 

所以这里发生了什么,你正在创造“承诺”作为承诺。 Promise基本上是处理异步任务的一种方式。当你得到承诺时,你需要解决它,就像你从http调用返回的值一样。但是,如果获得$ q,则您使用'then'而不是'success'。考虑下面的代码片段:

getData() 
    .then(function(data) { 
     $scope.spot = data.data; 
     console.log($scope.spot); 
    }) 

希望这会有所帮助。

UPDATE 如您例如通过处理错误,你可以这样做的:

getData() 
    .then(function(data) { 
     if(data.data) { 
      $scope.spot = data.data; 
      console.log($scope.spot); 
     } else { 
      console.log("its an err"); 
     } 
    }); 

或者这

getData() 
    .then(successCallback, errorCallback); 

function successCallback(data) { 
    $scope.spot = data.data; 
    console.log($scope.spot); 
} 

function errorCallback() { 
    console.log("its an err"); 
} 
+0

看起来不错,但我怎么现在处理HTTP错误? – 2014-10-18 14:29:58

+0

对不起...什么是$ q,我如何注入他? – 2014-10-18 14:30:44

+0

那么,如何处理http错误可能取决于我猜的用例。在控制器和/或服务中注入$ http的地方注入$ http。你曾经执行getData函数的地方。 – cbass 2014-10-18 14:33:43