Site icon ParallelCodes

AngularJS Services

AngularJS services are set of functions that performs a specific tasks. AngularJS has several inbuilt services like $http, $location, $scope, $rootScope. Inbuilt services generally starts with ‘$’ symbol. We can also create our own services.

AngularJS services features:

  1. Follows Single Responsibility Principle, meaning each functions performs only one single tasks.
  2. They are initiated only when an application component depends on it.
  3. Service factory assigns reference instance of a service to the dependent application component.
  4. They are substitutable objects wired together using Dependency Injection.
  5. We can use inbuilt services and a custom service across our app.
Example of a Service:

Below example demonstrates a very simple approach of creating a service using service method.

<html>
<head>
<title>AngularJS - Expressions JSON Objects</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<button ng-click="greet()">Show Greeting</button>
</div>
</body>

<script>
var app = angular.module("myApp",[]);

app.service('myService', function(){
this.alert = function()
{
alert('Hello World!');
}
});

app.controller('myController', function($scope,myService){
$scope.greet = function(){
myService.alert();
}
});

</script>
</html>

VIEW DEMO

OUTPUT:


Using $http service:

AngularJS $http service is one of the most commonly used service. It helps in posting data and getting response from Web APIs. It also handles any error if it occurs during the process. Below is an example of HttpGet request using $http service.

Example:

<html>
<head>
<title>AngularJS - Expressions JSON Objects</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body ng-app="myApp" style="padding: 10px;background-color: #f7f7f7;"></body>

<div ng-controller="myController">

<table class="table table-condensed" style="width: 500px;">
<tr ng-repeat='user in users.data'>
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.email}}</td>
<td><img ng-src="{{user.avatar}}"/></td>
</tr>
</table>
</div>
</body>

<script>
var app = angular.module("myApp",[]);

app.controller('myController', function($scope,$http){

var funSuccess = function(response)
{
$scope.users = response.data;
console.log(response.data);
};

var funError = function(response)
{
$scope.error = response.data;
};

$http({
method: 'GET',
url:'https://reqres.in/api/users?page=2',
}).then(funSuccess, funError);
});

</script>
</html>

VIEW DEMO

OUTPUT:


In the next part of this series we will learn more about $http service.


References: AngularJS API DOC

 

Exit mobile version