Nov 17, 2015
What is an Angular Service?
In my previous blog post I have used what we call an Angular Service, we used this service to communicate to a server and retrieve some information. In this blog, I will go into a little more detail about what an Angular Service is.
With an Angular service created, it can act as a proxy object that sits between your server and your website. Your Angular controllers then call the methods on the Angular service without knowing anything about the server’s business logic, this gives us a point of access that can potentially be used by the whole web page.
Angular services will be created lazily, which means they are only created when they are needed to satisfy a particular request. The benefit of services being created lazily is that during our testing we can inject alternative versions of the service that can simplify the testing process, this removes the complicated business logic out of the testing.
When you want to create a service in your Angular Module you can use one of the following approaches:
- The Factory method
- The Service method
- The Provider method
All these approaches expose their API’s through the use of methods and you can also inject other services into the service as arguments, such as the $http service if you want to perform send and receive information from the server.
Next, I will show you a code sample of a very simple Angular service created by using the Factory method. By using the other methods, you will follow a similar path to the method showcased here.
In the above code there are a few things to take note of:
- In line 3 you can see I use the .factory keyword to start my service
- This requires a name, in my case
- Optionally some input arguments, in my case I pass in the $http
- In line 4 I create a new instance of the service.
- In line 5 I create a method that the controller can call if it wants to implement the logic, in my case it is called simplemethod and it writes the famous Hello World
Finally, once you have your service created it won’t be used yet until you call it from somewhere. When using Angular services, it is independent of how you defined it as it will be used in the same way. Any controller or any other services can call upon the service by using the registered name, in my case I will use a basic controller to call the service method.
In the above code I have created a basic controller to call my service, I included the following:
In line 8, I used the controller function to create a controller and I passed in the SimpleSVC, this is the service name I have provided earlier. By passing in the service name your controller can now use that service.
In line 9, I called the simplemethod that resides in the SimpleSVC.
This concludes the basic need to know about what a service is as well as how to create and use the service.
For more information, have a look at New Horizons' Developing Responsive Websites using jQuery, AngularJS and Bootstrap course.