如何访问$ http.get调用者变量

时间:2015-11-01 16:36:20

标签: javascript angularjs scope angular-promise

考虑这个简单的angularjs代码:

$http.get( url ).then(function ( response ) {
    var cache = new Cache(url);
    cache.response = response;
});

我的问题是上面的代码是不确定的。有时,当从服务器获取响应时,url不匹配。

我想同时编辑10个联系人数据。 因此,为了实现这一点,我想将请求缓存到服务器并将其放入javascript对象中。

我已经编写了一个简单的服务来实现这一目标,但是遇到了上述错误。

以下是代码:

angular.module('myApp')
  .factory('save', function($http, $q) {

    // Private object
    var Cache = function(url) {
      this._url = url;
      this.response = {};
      this.saveDeferred = null;
      this.saveDeferredFulfilled = false;
    };

    Cache.prototype.$save = function () {
      return $http.put( this._url ).then(function (response) {
        this.response = response;
        return response;
      });
    };

    //public method
    var draft = {
      caches: {},
      get: function ( url ) {
        if (draft.caches.hasOwnProperty(url)) {
          return draft.caches.url.response;
        } else {
          return $http.get( url ).then(function ( response ) {
            var cache = new Cache(url);
            cache.response = response;
            return cache;
          });
        }
      },
      save: function(url) {
        if (draft.caches.url.saveDeferred) {
          if (!draft.caches.url.saveDeferredFulfilled) {
            draft.caches.url.saveDeferred.reject(new Error('forced timeout'));
          }
          draft.caches.url.saveDeferred = null;
          draft.caches.url.saveDeferredFulfilled = false;
        }

        draft.caches.url.saveDeferred = $q.defer();
        draft.caches.url.response.version = (parseInt(draft.caches.url.response.version) + 1).toString();

        $http.put(url, draft.caches.url.response)
          .success(function(data) {
            console.log('some data returned');
            console.log(data);
            draft.caches.url.saveDeferredFulfilled = true;
            draft.saveDeferred.resolve(data);
          })
          .error(function(error) {
            console.log('Some error occured in save.creates');
            console.log(error);
            draft.saveDeferred.reject(error);
          });
        return draft.saveDeferred.promise;
      }
    };

    return draft;
  });

它必须是非常基本的东西,我在这里缺少的东西。

0 个答案:

没有答案