Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a GET to an endpoint and print out data using Angular

I'm trying to make a GET to my endpoint and print data in my page

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>



<div ng-app="myApp" ng-controller="myCtrl">

  <p>Data is:</p>
  <h1>{{myData}}</h1>

</div>



<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope, $http) {

    var promise = $http({
      method: 'GET',
      url: 'http://d.biossusa.com/api/distributor?key=*****',
      dataType: 'jsonp',
    });

    promise.success(function (data, status, header, config) {
      console.log("status is ", status);
      console.log(config.method + " data is: " + config.data);
      console.log("data is ", data);
      $scope.myData = response.data;

    });

  });

</script>

I kept getting

enter image description here

I am expected to get the data printing out !

https://jsfiddle.net/bheng/b3rgh92v/

When I curl this url : http://d.biossusa.com/api/distributor?key=*****

I got the result fine !

enter image description here

What did I do wrong on my angular ? Any hints ?

like image 374
code-8 Avatar asked Jan 28 '17 00:01

code-8


People also ask

Can I use fetch in angular?

I don't think there is a reason to use Fetch in Angular as the existing xhr service is fine. There are pro and cons with both which are already well documented on the internet so will not cover that here. You can see the Angular xhr backend service here.


1 Answers

Few observations:

1): Make sure you have added the reference of your script file in your html if you are using external file (where you are creating angular module).

2): Remove response from your assignment

$scope.myData = response.data;  //response is undefined, so remove it

It should be

$scope.myData = data;

3) Lastly, make sure you are allowed to call that endpoint [I get an error saying I can't call http endpoint from plnkr's HTTPS endpoint so I updated the GET URL]. I tried your code in plunker with a different URL and it worked ok with the above changes. Here is plnkr link

like image 179
Ali Baig Avatar answered Oct 01 '22 15:10

Ali Baig