How to use AngularJS Services

  • Finally the ‘finally’ block of statements are executed regardless of success/failure.
  • $scope.callService = function(postObj) { $scope.loading = true; serviceModuleName.postLaunch(postObj) .then(function (data) { $scope.returnedData = data; }) .catch(function (err) { $scope.error = ‘Sorry something went wrong! ‘
  • (Services can be implemented by either angular service or angular factory)
  • Since a promise is being returned by the service we need to handle it with then, catch and finally blocks. ‘
  • When we write a service, the main goal is to be make it modular and reusable.

There are many ways in which one can use Angular Services in an Angular project. The following is a good example of a frequent use case for the angular factory. (Services can be implemented by either angular service or angular factory)

@collegestash: How to use AngularJS Services

There are many ways in which one can use Angular Services in an Angular project. The following is a good example of a frequent use case for the angular factory. (Services can be implemented by either angular service or angular factory)

When we write a service, the main goal is to be make it modular and reusable. In the following service named ‘serviceModuleName’, we have added support for HTTP GET & POST calls. We are handling them using promises being returned. For this purpose we use the $q service in angular.

Define a Service

(function () { ‘use strict’; angular.module(‘App’).factory(‘serviceModuleName’, function ($http, $q) { var httpDeferGet = function (url) { var deferred = $q.defer(); $http.get(url) .then(function successCallback(response) { deferred.resolve(response.data); }, function errorCallback(response) { deferred.reject(response.status); }); return deferred.promise; }; var httpDeferPost = function (url, obj) { var deferred = $q.defer(); $http.post(url, obj) .then(function successCallback(response) { deferred.resolve(response.data); }, function errorCallback(response) { deferred.reject(response.status); }); return deferred.promise; }; var getLaunch = function () { return httpDeferGet(‘www.example.com/test-get-endpoint’); }; var postLaunch = function (obj) { return httpDeferPost(‘www.example.com/test-get-endpoint’, obj); }; return { getLaunch: getLaunch, postLaunch: postLaunch } }); })();

Injecting a Service into the Controller

var app = angular.module(‘myApp’, []); app.controller(‘myCtrl’, function($scope, serviceModuleName) { });

Calling a Service from inside a Controller

Since a promise is being returned by the service we need to handle it with then, catch and finally blocks. ‘then’ returns the data, ‘catch’ catches the exception thrown and it can be handled here. Finally the ‘finally’ block of statements are executed regardless of success/failure.

How to use AngularJS Services

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.