27.03.2017 Views

ng-book

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Services 159<br />

Now, anywhere that we need to access the GitHub API, we no lo<strong>ng</strong>er need to call it through $http;<br />

we can call the githubService instead and let it handle the complexities of deali<strong>ng</strong> with the remote<br />

service.<br />

The GitHub API exposes the activity stream for the user on GitHub (this stream is simply a list of<br />

recent events that a user has logged on GitHub). In our service, we can create a method that accesses<br />

this API and exposes the resulti<strong>ng</strong> set to our API.<br />

To expose a method on our service, we can place it as an attribute on the service object.<br />

a<strong>ng</strong>ular.module('myApp.services', [])<br />

.factory('githubService', function($http) {<br />

var githubUrl = 'https://api.github.com';<br />

var runUserRequest = function(username, path) {<br />

// Return the promise from the $http service<br />

// that calls the Github API usi<strong>ng</strong> JSONP<br />

return $http({<br />

method: 'JSONP',<br />

url: githubUrl + '/users/' +<br />

username + '/' +<br />

path + '?callback=JSON_CALLBACK'<br />

});<br />

}<br />

// Return the service object with a si<strong>ng</strong>le function<br />

// events<br />

return {<br />

events: function(username) {<br />

return runUserRequest(username, 'events');<br />

}<br />

};<br />

});<br />

The githubService contains a si<strong>ng</strong>le method that the components in our application can call.<br />

Usi<strong>ng</strong> Services<br />

To use a service, we need to identify it as a dependency for the component where we’re usi<strong>ng</strong> it: a<br />

controller, a directive, a filter, or another service. At run time, A<strong>ng</strong>ular will take care of instantiati<strong>ng</strong><br />

it and resolvi<strong>ng</strong> dependencies like normal.<br />

To inject the service in the controller, we pass the name as an argument to the controller function.<br />

With the dependency listed in the controller, we can execute any of the methods we define on the<br />

service object.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!