Services in AngularJs

The biggest thing apart from two – way data binding introduced by AngularJs, has been services and dependency injections. They have both made unit testing possible, which was a bit of mess before and also the whole MVC architecture and controllers, which have given the code a separate components and module to work on has been awesome. This blog is dedicated to know exactly what services are, and how to use them efficiently in your code.Now, Angular 8 is in the market, so this is definitely bit tedious than how simpler they have made it now.

Why Services?

AngularJs provides support for built in services like $http, $controller, $filter but most of the times you would be creating  your own services. Now, the whole concept of Dependency injection is to have a reusable  plug-in code, to call anytime. And that’s what services are for, you would be using services methods for fetching data from server, and making multiple get, put, post requests at all times. Now, say we have an e-commerce site where in Database you have record of client. Now, that record is needed to display  client profile, fulfilling  purchase order, the same service can be called at multiple controllers to fetch the data. And that’s code reusability at its best!

Code:

var app = angular.module(‘myApp’, []);
app.controller(‘myController’function($scope, $http) {
$http.get(“/api/getData”).then(function (response) {
$scope.dataOfClient= response.data;
});
});

< div ng-controller="MyController">
</div>

Working:

myApp is the angularJs application. And myController is the controller called at front-end.  $http is the inbuilt service used here.  Get() hit the api at getData() method, which returns the data. Which is then stored as $scope.dataOfClient;

Pictorial Depiction:

 

Hope, it would have made you clear with the  concept. If you still have an any doubt, leave it in the comment section below. Our team would revert back within 24 hours.

Do Follow our Facebook page https://www.facebook.com/lovebeingengineer/.

Similar Blogs:

Top 10 AngularJs Interview Questions

 

AngularJs Vs Angular

 

Forms in AngularJs

 

$scopes in AngularJs

 

Controllers in AngularJs

Understanding Two-Way Data Binding in AngularJs

 

Journey of Angular

 

Dependency Injection in AngularJs!

 

Templates And Expressions in AngularJs

 

Leave a Reply