HTTP based Rest Service in Angular JS using Yeoman
Service Oriented applications are implemented as a set of services working together to achieve a single objective. In this post we are going to learn how we can use REST based HTTP services from an angular-js client. Here we are using GitHub http service to get the details about a user.
This service would be defined for an application which is created using Yeoman. Let’s first add service github-user-service from command prompt using yo‘s angular:service generator.
This would result in creating a skeleton service in app’s service folder. Additionally, yo would add a file for writing unit tests for this service. Yes I am using Visual Studio Code.
Yo would remove all hyphens in the service name provided to the generator and replace them with upper-casing the following letter. So our github-user-service has become githubUserService. Now we are injecting $http and $q default services to this service. $http helps us in using HTTP based REST resources.
Since this is an external call which might have an inherent delay, we shouldn’t be blocking the caller. So we have also injected $q, which allows us to introduce promises to our design. As soon as we make HTTP call, we return the promise to the caller. As we receive a response, we are keeping our promise, and using the defer object created using $q to return the resolved data. In case of an error, $http provides error callback, which can be used to break our promise using defer’s reject method.
A service can be injected in a controller. Here we are injecting githubUserService to a controller. Since getUserDetailsPromise returns a promise, we can add callbacks for the cases where it is keeping and rejecting the promise. The first function is for the case where it keeps the promise. Here we are just writing the returned user details to the console. But before that we are just converting the javascript’s json object to a sting using JSON.stringify.
Let’s run the above app, it successfully calls github’s user service and prints the result on the console.
You must log in to post a comment.