zoukankan      html  css  js  c++  java
  • angularJs中缓存数据,免去重复发起请求的几种写法

    带缓存处理的两种写法

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

    在线浏览

    写法1:

        function demo(){
          if (demo.cache == undefined) {
            return $http.get('https://api.github.com/users/github')
              .then(function(data, status, headers){
                demo.cache = data.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(){
          let deferred = $q.defer(), that = this;if (that.cache == undefined) {
            $http.get('https://api.github.com/users/github')
              .success(function(data, status, headers){
                that.cache = data;
                deferred.resolve(that.cache);
              })
          }else {
            console.log('from cache');
            deferred.resolve(that.cache);
          }
          return deferred.promise; 
        }
    
    
        // 点击加载
        $scope.load = function() {
          demo().then(function(data){
            $scope.list = data;
          })
        }

    写法3 利用闭包缓存结果

        // 利用闭包缓存结果
        function demo2() {
          let defer = $q.defer(), cache;
          return function() {
            if (cache == undefined) {
              $http.get('https://api.github.com/users/github')
                  .then((res) => {
                      cache = res.data;
                      defer.resolve(cache);
                  })
            }else {
              console.log('from cache');
              defer.resolve(cache);
            }
            return defer.promise;
          }
        }
    
        // 点击加载
        let startDemo = demo2();
        $scope.load = function() {
          startDemo().then(function(data){
            $scope.list = data;
          })
        }
  • 相关阅读:
    SpringCloud就是分布式啊?!?!?!
    有没有可能让运算符作为函数参数?
    【问题】用C++结构体实现顺序表,数据超过数组长度后,表长自动+1
    数学模型与数据结构的丝连
    最浅显易懂的数据库索引讲解
    whois 信息
    旁站C段查询
    网络搜索引擎
    服务指纹识别
    绕过CDN查找ip方法总结
  • 原文地址:https://www.cnblogs.com/mafeifan/p/6223259.html
Copyright © 2011-2022 走看看