Search code examples
httpangularjsangularjs-service

angular service and http request


creating service

myApp.factory('serviceHttp', ['$http', function(http) {
  http.get($scope.url).then(function(result){
    serviceVariable = result;
  }
  return serviceVariable;
}

Controller

function appController($scope, serviceHttp){
  $scope.varX = serviceHttp;
  if(serviceHttp){
    // decision X;
  } else {
    // decision Y;
  }
}

view:

input(ng-if='varX') serviceHttp Exist
input(ng-if='!varX') serviceHttp noExist

The above code always shows varX not exist because app installs during http call of service. I want to use angular service to inject variables from server to make decision at time of booting the application.


Solution

  • Try to rewrite factory by this way that returns promise:

    myApp.factory('serviceHttp', ['$http', function(http) {
    
       var factory = {
           query: function () {
              var data = http.get($scope.url).then(function(result){
                  return result;
               },
              function (result) {
                alert("Error: No data returned");
             });
               return data;
           } 
       }
       return factory;  
    }]);
    

    From controller:

    serviceHttp.query().then(function (result) {
        $scope.varX =  = result;                            
    }
    

    Here is Demo Fiddle

    in demo we used other URL source