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

后端 未结 7 1445
轻奢々
轻奢々 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条回答
  •  离开以前
    2020-11-29 17:21

    No need to promise with $http, i use it just with two returns :

     myApp.service('dataService', function($http) {
       this.getData = function() {
          return $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){
            return data;
          }).error(function(){
             alert("error");
             return null ;
          });
       }
     });
    

    In controller

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

提交回复
热议问题