简体   繁体   中英

One time call http request using angularjs

  function get (id, ignore) {
    var deferred = $q.defer();

    $http.get('v1/info/' + id, {
      ignoreAuthModule: ignore
    })
      .success(function (data) {
        deferred.resolve(data.data);
      })
      .error(function (reason) {
        deferred.reject(reason.message););
      });

    return deferred.promise;
  }

init();

function init(){
 users.get($routeParams.id)
    .then(function (data) {
        if(data.has_something === 1){
          $scope.hasSomething = true;
        }else{
          $scope.hasSomething = false;
        }

    });
}

I have a Service that get the information about user using promise and Fetching information from the service with init function //if i call init function this should call two times one from function initialization and other i'm calling it from service how can i stop two times calling api I mean it should call one time if already called

You're using the explicit promise creation antipattern here, and your code could be much simpler. Here is how you can use memoization to avoid requesting the same user twice:

.factory('users', ['$http', function ($http) {
    var userPromises = {};

    function get (id, ignore) {
        if (!userPromises[id]) {
            userPromises[id] = $http.get('v1/info/' + id, {
                ignoreAuthModule: ignore
            })
            .then(function (data) {
                return data.data;
            })
            .catch(function (reason) {
                throw new Error(reason.message);
            });
        }

        return userPromises[id];
    }

    return {
        get: get
    };
});

You can assign your deferred.promise to some variable and then return that variable, and before your http call just check whether that variable is already defined or not

function get (id, ignore) {
  if (angular.isUndefined(user)) {
    var deferred = $q.defer();

    $http.get('v1/info/' + id, {
      ignoreAuthModule: ignore
    }).then(function(response) {
      if (response.status == 200) {
        deferred.resolve(response.data);
      } else {
        deferred.reject(response.data);
      };

    user =  deferred.promise;
    return user;
   } else {
    return user;
   }
  }

This way your api will get called only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM