简体   繁体   中英

proper way to call http (RESTFUL WebAPI) in angularjs

I have following controller code

module.registerController('DemoCtrl', function ($scope, myFactory) {
        myFactory.get(function (data) {
            console.log(data); /// data is always undefined 
        });
    });

and following the factory which is calling restful webapi

module.registerFactory('myFactory', ['$http',
    function ($http) {
            function get(callback) {
                $http.get('mywebapiurl')
                    .success(function (response) {
                        //debugger; data comes back from server
                        callback(response);
                    }).error(function (response, status, headers, config) {
                        callback(response);
                    });
            }

        return {
            get: get
        }
    }]);

The factory is calling webapi service and does gets the data back. However in controller the data doesnt get returned.

Am I missing something obvious here? Also not sure if this is the best way to call webservice in angularjs in controller using factory. Any inputs are most welcome.

Thanks,

controller code

module.registerController('DemoCtrl', function ($scope, myFactory) {
    myFactory.get("url").then(function(d) {
            console.log(d.data); 
        }
    });
});

factory which is calling restful webapi

module.registerFactory('myFactory', ['$http',
function ($http) {
         var apiFactory = {
               get:function(url){
                   return $http.get(url);
               }
         }
    return apiFactory;
}]);

Success and failure in factory

module.registerFactory('myFactory', ['$http',
function ($http) {
     var apiFactory = {
           get:function(url){
               return $http.get(url).then(function(response){
                      // success
                      return responce.data;
               },function(error){
                      //failure
                      return error;
               };
           }
     }
    return apiFactory;
}]);

You want to return a promise instead of passing a callback. As $http.get already returns a promise, you can just return that, or a derived promise that returns the response data directly. By the way, your factory looks like it should be a service instead:

angular.moudule('yourApp')
.service('myService', ['$http', myService]);

function myService($http) {
    this.get = function(url) {
        return $http.get(url)
                   .then(function transformData(response){
                       return response.data;
                   }).catch(function onError(rejectionResponse){
                       //Whatever you want to do here
                   });
    }
}

This way myService.get will return a promise you can .then() , .catch() and .finally() on what you want, staying in the frameworks coding style. For example:

var squirrels = [];
myService.get('http://squirrelshop.com/api/squirrels')
    .then(function(squirrelsData){
        console.log('Got the squirrels!');

        squirrels = squirrelsData;
    }).catch(function(rejection){
        console.warn('Couldnt fetch squirrels. Reason: ' + rejection);
    });

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