Best way to invoke Rest APIs from angularjs?

后端 未结 6 408
遇见更好的自我
遇见更好的自我 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 19:12

    You can use either resources, or build services that implement http calls.

    If you want to use resources, remember:

    1. to include the angular-resource.js file which you can find here
    2. to include in your module declaration to include the ngResource module dependency like so: angular.module('myApp',['ngResource'])

    After that you can declare a resource in this fashion:

    function MyController($scope, $resource){
      var User = $resource('/user/:userId', {userId:'@id'});
      var user = User.get({userId:123}, function() {
        user.abc = true;
        user.$save();
      });
    }
    

    Alternatively, use services if you need a much deeper level of granularity such as

    angular.module('myApp')
    .factory('MyAPIService', function($http){
      var apiurl, myData;
      return {
        getData: function(){
          $http.get(apiurl)
          .success(function(data, status, config, headers){
            myData = data;
          })
          .error(function(){ //handler errors here
          });
        },
        data: function() { return myData; }
      };
    });
    

    I find services to be great because of the ability to share data between controllers, so you can inject them in a controller like so

    myapp.controller('MyController', function($scope, MyAPIService){
      $scope.data = MyAPIService.data();
      // etc.
    
    });
    

提交回复
热议问题