加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 处理$http响应服务

发布时间:2020-12-17 09:32:26 所属栏目:安全 来源:网络整理
导读:我最近发布了一个详细的描述我面临的问题 here在SO。由于我不能发送实际的$ http请求,我使用超时模拟异步行为。从我的模型到视图的数据绑定工作正常,借助@Gloopy 现在,当我使用$ http而不是$ timeout(本地测试)时,我可以看到异步请求成功,数据在我的服
我最近发布了一个详细的描述我面临的问题 here在SO。由于我不能发送实际的$ http请求,我使用超时模拟异步行为。从我的模型到视图的数据绑定工作正常,借助@Gloopy

现在,当我使用$ http而不是$ timeout(本地测试)时,我可以看到异步请求成功,数据在我的服务中用json响应填充。但是,我的观点不是更新。

更新Plunkr here

这是一个Plunk,做你想要的: http://plnkr.co/edit/TTlbSv?p=preview

这个想法是,你直接使用promises和他们的“then”函数来操作和访问异步返回的响应。

app.factory('myService',function($http) {
  var myService = {
    async: function() {
      // $http returns a promise,which has a then function,which also returns a promise
      var promise = $http.get('test.json').then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl',function( myService,$scope) {
  // Call the async method and then do stuff with what is returned inside our own then function
  myService.async().then(function(d) {
    $scope.data = d;
  });
});

这里是一个稍微复杂的版本,缓存请求,所以你只有第一次(http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview):

app.factory('myService',function($http) {
  var promise;
  var myService = {
    async: function() {
      if ( !promise ) {
        // $http returns a promise,which also returns a promise
        promise = $http.get('test.json').then(function (response) {
          // The then function here is an opportunity to modify the response
          console.log(response);
          // The return value gets picked up by the then in the controller.
          return response.data;
        });
      }
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl',$scope) {
  $scope.clearData = function() {
    $scope.data = {};
  };
  $scope.getData = function() {
    // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
      $scope.data = d;
    });
  };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读