首页 > Web开发 > 详细

angularJs中$q的两种写法

时间:2016-12-26 18:39:09      阅读:266      评论:0      收藏:0      [点我收藏+]

带缓存处理的两种写法

过程:点击button触发load()方法,请求数据成后显示到页面中。如果已经请求过则从缓存中读取。

在线浏览

写法1:

    function demo(){
      if (demo.cache == undefined) {
        return $http.get(‘https://api.github.com/users/github‘)
          .success(function(data, status, headers){
            demo.cache = data;
            return $q(function (resolve, reject) {
              resolve(demo.cache);
            });
          })
      }else {
        console.log(‘from cache‘);
        return $q(function (resolve, reject) {
          resolve(demo.cache);
        });
      }
    }


    // 点击加载
    $scope.load = function() {
      demo().then(function(data){
        $scope.list = data.data;
      })
    }

写法2:

感觉第二种写法好些,注意细节。

    function demo(){
      var deferred = $q.defer();
      if (demo.cache == undefined) {
        $http.get(‘https://api.github.com/users/github‘)
          .success(function(data, status, headers){
            demo.cache = data;
            deferred.resolve(demo.cache);
          })
      }else {
        console.log(‘from cache‘);
        deferred.resolve(demo.cache);
      }
      return deferred.promise; 
    }


    // 点击加载
    $scope.load = function() {
      demo().then(function(data){
        $scope.list = data;
      })
    }

 

angularJs中$q的两种写法

原文:http://www.cnblogs.com/mafeifan/p/6223259.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!