Introduction To AngularJS Services

Introduction To #AngularJS #Services by @IamJasbeerSingh cc @CsharpCorner  #Framework #App

  • Making separation of concerns possible, i.e. the property of AngularJS. Some examples of the inbuilt Services are $https, $route, $location, $window etc.
  • Let’s use an inbuilt Service to check what will be the benefit and how we can use the Services.
  • We can create the Services, using three ways.
  • By using Service method, we get an instance of a function passed to “module.service” and by using factory method, we get the value, which is returned by invoking the function reference, which is is passed to module.factory.
  • In the article, we have seen how the Services can be created as per use and how can we use inbuilt Services.

This article is about Angular Services. This will give you a brief idea about Angular Services and how can we create our own services.

@CsharpCorner: Introduction To #AngularJS #Services by @IamJasbeerSingh cc @CsharpCorner #Framework #App

AngularJS is a JavaScript Framework, which is very powerful and its library is written in JavaScript. This framework is used to make single page applications. From this definition, you should get an idea that if we want to make a Single Page application, AngularJS is the answer as the most powerful JavaScript Framework. AngularJS extends HTML with new attributes. AngularJS allows us to write the applications in a clean Model-View-Controller way.

A Service is a function or an object; it is limited to our AngularJS application. We can make our own Services and can use one of many inbuilt Services. The Services are injected, using dependency injection mechanism. AngularJS has many inbuilt Services. Services are JavaScript functions, which are responsible to do a specific task only. This is the property of individual identity, which is maintainable and testable. Thus, making separation of concerns possible, i.e. the property of AngularJS. Some examples of the inbuilt Services are $https, $route, $location, $window etc. Angular only instantiates a Service when an application component depends on it. Each component is dependent on a Service, which gets a reference to the single instance generated by the Service factory.

Let’s use an inbuilt Service to check what will be the benefit and how we can use the Services. Let’s use $location, $location is a Service that has methods, which returns information about the location of the current Webpage. Now, we will also see the use of dependency injection mechanism. The Service will be defined as a dependency.

Now, we will see how we can use them.

Let’s understand this with an example given below.

Now, we can see all the three ways. If we run this, we will get the output given below.

Introduction To AngularJS Services