How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

后端 未结 7 1464
轻奢々
轻奢々 2020-11-29 16:58

I have the following code in the controller.js,

var myApp = angular.module(\'myApp\',[]);

myApp.service(\'dataService\', function($http) {
delete $http.def         


        
7条回答
  •  萌比男神i
    2020-11-29 17:45

    I suggest you use Promise

    myApp.service('dataService', function($http,$q) {
    
      delete $http.defaults.headers.common['X-Requested-With'];
      this.getData = function() {
         deferred = $q.defer();
         $http({
             method: 'GET',
             url: 'https://www.example.com/api/v1/page',
             params: 'limit=10, sort_by=created:desc',
             headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         }).success(function(data){
             // With the data succesfully returned, we can resolve promise and we can access it in controller
             deferred.resolve();
         }).error(function(){
              alert("error");
              //let the function caller know the error
              deferred.reject(error);
         });
         return deferred.promise;
      }
    });
    

    so In your controller you can use the method

    myApp.controller('AngularJSCtrl', function($scope, dataService) {
        $scope.data = null;
        dataService.getData().then(function(response) {
            $scope.data = response;
        });
    });
    

    promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.

提交回复
热议问题