Best way to invoke Rest APIs from angularjs?

后端 未结 6 410
遇见更好的自我
遇见更好的自我 2020-12-28 18:44

From where should REST API request be invoked from angular js?

I.e. from controller, module, service, factory. I am totally confused that what should be the right w

6条回答
  •  轮回少年
    2020-12-28 18:59

    This is how we do this, Write the http service as a factory method.

    Edited as per comments to use Promise API

     var MyApp = angular.module('App', []);
    
     MyApp .factory('ApiFactory', ['$http',
            function ($http) {
                return {
                   getUsers: function (rowcount) {
                    var promise = $http.get('api/Users/' + rowcount) .then(function(response) {
                    return response.data;
                  }, function (error) {
                    //error
                })
                return promise;
               }
             }
           }
       ]);
    

    Now you can use it in controller as this.

    MyApp .controller('MyController', ['$scope', 'ApiFactory',
      function ($scope, ApiFactory) {
    
        $scope.Users = null;
    
        ApiFactory.getUsers(count).then(function(data)
        {
          $scope.Users = data;
        });
     } 
     ]);
    

提交回复
热议问题