Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

AngularJS Services

In AngularJS, you can create your own service or utilize one of the many built-in services available.

What is a Service?

In AngularJS, a service is a function or object that is accessible and specific to your AngularJS application.

AngularJS provides around 30 built-in services, one of which is the $location service.

The $location service offers methods that return information about the current web page’s location.

Example

Utilize the $location service within a controller.

var app = angular.module(‘myApp’, []);
app.controller(‘customersCtrl’function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});

Keep in mind that the $location service is included as an argument in the controller. To use the service within the controller, it must be declared as a dependency.

Why use Services?

For many services, such as the $location service, you could use existing objects from the DOM, like the window.location object; however, doing so may impose some limitations on your AngularJS application.

AngularJS continuously monitors your application, and to manage changes and events effectively, it is recommended to use the $location service instead of the window.location object.

The $http Service

The $http service is one of the most widely used services in AngularJS applications. It sends requests to the server and allows your application to process the response.

Example

Utilize the $http service to fetch data from the server.

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’function($scope, $http) {
  $http.get(“welcome.htm”).then(function (response) {
    $scope.myWelcome = response.data;
  });
});

The $timeout Service

The $timeout service in AngularJS is a version of the window.setTimeout function.

Example

Show a new message after a two-second delay.

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’function($scope, $timeout) {
  $scope.myHeader = “Hello World!”;
  $timeout(function () {
    $scope.myHeader = “How are you today?”;
  }, 2000);
});