user1511443
user1511443

Reputation: 175

Best Way to implement $http in Angular JS?

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??

Upvotes: 1

Views: 1968

Answers (3)

Aniket Jha
Aniket Jha

Reputation: 1781

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;
        }); 
    }
}

Upvotes: 0

Shai Reznik - HiRez.io
Shai Reznik - HiRez.io

Reputation: 8948

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.

Upvotes: 5

Arshabh Agarwal
Arshabh Agarwal

Reputation: 556

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'];
  })
  }

Upvotes: 0

Related Questions