1

What is the best method to use a $http service in angular JS? How can we achieve the promise paradigm and do the best Any help would be appreciated.

I have gone thru the API developer's guide and found the following..

 $http.get(url)

I was wondering what would the promise call would look like and how do i attach a callback function to this??

1
  • 1
    $http.get() is just a shortcut method where method: GET is already defined for you. So, any $http() examples you see in the docs that use promises also apply to $http.get(). Commented Jan 29, 2013 at 22:43

3 Answers 3

5

Any call to $http returns a promise object, so you can then call the success method or error like this:

$http.get("/url").success(function(data){ 

})
.error(function(errorData, errorStatus){

})

or you can do this:

var promise = $http.get("/url");

promise.success(...)

Make sure you read about $resource, $q and $http to cover the "angular" way.

Sign up to request clarification or add additional context in comments.

Comments

0

The best way to implement a callback is something like this

  $http(url).then( function (){
      return //values
   })

Now if you want to achieve the promise paradigm you need to have a resolve config in your controller

resolve: {
   value1: return $http.get(url).then( function (response){
      if(response)
         return response.data['value'];
  })
  }

Comments

0

Standard Way (industry)

Make a js folder. Inside this folder make another folder name it utils.

As $http request will be made several times it is better to keep it separately. Make an AngularJS factory file and call it jsonLoader.js.

jsonLoader.js:

app.factory("jsonLoader",function($http,$q){
   var object={
    loadJson(json){
        var defer=$q.defer();
//json url of ur data
        var jsonUrl="http://localhost:3000/jsonData/"+json+".json";

        $http.get(jsonUrl).then(function(resolveData){
            defer.resolve(resolveData);//recivedData  
        },
        function(rejectedError){
            console.log("Rejected error from jsonLoader ",rejectedError);
        }
        );
        return defer.promise;
    }
   }
   return object;
});

Now in your controller inject this factory like this:

app.controller("mainController",function($scope,mainFactory,jsonLoader){
    $scope.loadNavMenu=()=>{
        console.log("controller");
        var promise =jsonLoader.loadJson('navMenu');
        promise.then(function(recivedData){
            console.log("Data is ",recivedData.data);
//callback function here or some data binding 
            $scope.menuItems=recivedData.data.menuItems;
        }); 
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.