Custom Services

AngularJS makes it very easy to create our own services: All we need to do is register the service.

Once a service is registered, the Angular compiler can reference it and load it as a dependency for

runtime use. The name registry makes it easy to isolate application dependencies for mocks and

stubbing in our tests.

Placing application’s business logic and common operations in a single place, is always a good design. This improves code re-usability and avoid code duplication. You should put all such logic in custom angular services. This makes code modular and more maintainable.

Further, your code becomes more testable. Remember, angular provides first class support for unit testing. Thus we can quickly write tests for these services and avoid many possible defects.

There are mainly two ways to declare angularjs services. Let’s understand both ways:

Using – module.service( ‘serviceName’, function(){} )

When you create a service using module.service(), an instance of the function() passed as second parameter becomes the service object that AngularJS registers and injects later to other services / controllers when asked for.

The syntax for declaring methods in custom service object using module.service() is :

module.service(‘DemoService’, function() {

//”this” will be used as service instance

this.firstMethod = function() {

//..

}

this.someOtherMethod = function() {

//..

}

});

Using – module.factory( ‘factoryName’, function(){} )

When you create a service using module.factory(), return value of function() passed as second parameter becomes the service object that AngularJS registers and injects later to other services / controllers when asked for.

The syntax for declaring methods in custom service object using module.factory() is :

module.factory(‘DemoService’, function() {

//”factory” will be used as service instance

var factory = {};

factory.firstMethod = function() {

//..

}

factory.someOtherMethod = function() {

//..

}

return factory;

});

Built-in Services
Other AngularJS Services

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?