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.
Let’s run the above app, it successfully calls github’s user service and prints the result on the console.