AngularJS回调,复制$http的行为.将缓存转化为承诺

AngularJS callback, copy the behavior of $http. Turn cache into promise

本文关键字:缓存 承诺 回调 复制 http AngularJS      更新时间:2023-09-26

我想为我的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方法完美配合,但不会与我的"缓存"一起工作,因为"缓存"应该具有以下回调:success&错误,如何创建它们?

这是因为$http返回了一个promise。您可以使用$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;
} 

所以,这里发生的事情,你正在创造"deffered"作为一个承诺。Promise基本上是处理异步任务的一种方式。当您得到一个promise时,您需要解决它,就像您对http调用的返回值所做的那样。但是对于$q deffered,您使用的是"then"而不是"success"。考虑下面的代码片段:

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

希望这能有所帮助。

更新例如,通过处理错误,您可以这样做:

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");
}