Friday, November 4, 2016

How to make an API call in an AngularJS 1.5.8 application.

Alright, starting with the very simple application I suggest here, I am going to revamp my token controller from:

app.controller("myCtrl", function ($scope) {
   $scope.firstName = "John";
   $scope.lastName = "Doe";
});

 
 

...to...

app.controller("myCtrl", function ($scope, apiGetter) {
   $scope.currentUrl = "http://www.anapioficeandfire.com/api/books";
   var content = apiGetter.goGetIt($scope.currentUrl);
   console.log(content);
});

 
 

I bet you can kinda tell what the revamped myCtrl is gonna to do, right? It's gonna hit the http://www.anapioficeandfire.com/api/books endpoint and barf what it collects from it up to the console. It is going to use apiGetter to do its magic, right? What is that. That's a service. I followed this for that! It appears you may just list the names of services you want in scope in a controller as variables in the function signature for the controller. My service looks like this:

app.service("apiGetter", function ($http) {
   
   return ({
      goGetIt: goGetIt
   });
   
   function goGetIt(whereToLookTo) {
      var request = $http({
         method: "get",
         url: whereToLookTo
      });
      return (request.then(handleSuccess, handleError));
   }
   
   function handleError(response) {
      alert('something went wrong');
   }
   
   function handleSuccess(response) {
      return (response.data);
   }
   
});

 
 

The last of the links I give suggests the three functions are "methods" and makes a distiniction between public and private methods. The goGetIt method is made public by way of being on the object in the return above all the methods. You could have many comma-seperated methods as properties here if you need more than one. It took me a while to realize that I needed to add goGetIt to what is returned in order for myCtrl to be able to use it dotting off of apiGetter. That is what makes it "public" so to speak.

No comments:

Post a Comment