Rayan958
Rayan958

Reputation: 17

Retrieve get response http angular

I am a beginner in angular and I want to retrieve the http get response of an url (http://myurl.com) to make after some manipulations.

I test that but no result :/

var app = angular.module('plunker', []);

app.factory('myService', function($http) {
  return {
    async: function() {
     return $http.get('http://apibuilder-apidiscovery.kermit.rd.francetelecom.fr/infrastructures/16857');
    }
  };
});

app.controller('MainCtrl', function( myService,$scope) {
  myService.async().then(function(d) { //2. so you can use .then()
    $scope.data = d;
  });
});

HTML

<body>
    <div ng-controller="MainCtrl">
        Data: {{data}}<br>
    </div>
</body>

Thank you so much.

Upvotes: 0

Views: 241

Answers (2)

Nikhil Mohanan
Nikhil Mohanan

Reputation: 1260

script.js

var app = angular.module('plunker', []);

app.factory('myService', function($http,$q) {

    var myService = {
        async : async,
    };
    return myService;

    function async() {
        var d = $q.defer();
        $http({
            method: 'GET',
            url: 'http://apibuilder-apidiscovery.kermit.rd.francetelecom.fr/infrastructures/16857',
            headers: {
                "Content-Type": "text/plain",
                // you can add headers here
            }
        }).then(function(reply) {
            d.resolve(reply.data);
        }, function(error) {
            d.reject(error.data);
        });
        return d.promise;
    }

});

app.controller('MainCtrl', function(myService, $scope) {

  myService.async()
    .then(function(result) {
        $scope.data = result;
  });

});

and the index file,

<!DOCTYPE html>
<html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="plunker" ng-controller="MainCtrl">
    Data: {{data}}<br>
  </body>

</html>

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

The data assignment should be $scope.data = d.data;

Controller

app.controller('MainCtrl', function( myService,$scope) {
  myService.async().then(function(d) { //2. so you can use .then()
    $scope.data = d.data;
  }, function(error){
     console.log('Error occured');
  });
});

Note also make sure that if you are trying to make call to external domain, the CORS should be enabled. Additionally you might need to pass autherization headers in the request.

Upvotes: 1

Related Questions