Understanding Providers, Services, and Factories in Angular

I’ve read quite a few posts (as well as questions posed) about the differences between services and factories in Angular. I’ve seen just as many attempts to explain it and even fell victim to trying to force an explanation for the difference myself. The answer is more simple than you may think and is evident if you browse the Angular source code and then re-read the documentation. When this clicked for me I had to share it because so many people seem to make more out of it than it is.

The biggest misconception I see is the idea that factories and services have anything to do with being a singleton. The reality is that both methods create singletons (unless you game them to generate new instances).

So here it is. I’m going to summarize then follow up with some examples;

  • Use a service when you want to pass a constructor function. The function will be invoked with the “new” operator and the result stored.
  • Use a factory when you want to return the object from a function (i.e. factory pattern). The function will be called and the result stored.
  • Use a provider when you want to be able to provide module-wide configuration for your object before making it available.

That’s it! It’s real simple. The key to note first is that factories and services end up with the same result, they just use different approaches. With the factory approach you can specify a function to resolve your dependencies and then return an object that uses them, like this:

app.factory(‘myAlertFactory’, [‘myAlert’, function (myAlert) {
return {
alert: function (message) {
myAlert.alert(message);
}
};
}]);

Notice that the outer function takes a dependency on a service called “myAlert”. Angular will wire that dependency, call your function and store the result. In this case I pass back an object with an alert method that “passes through” to the alert method on the myAlert service. Essentially I’ve created a “myAlertFactory” object I can use to reference that is a proxy to the underlying “myAlert” object.

The problem with the factory approach is that some languages like TypeScript lean you towards a more class-based approach, and other languages like CoffeeScript enforce it. You can’t just return an arbitrary object from the factory function, so instead you need a way to pass the type onto Angular (remember in JavaScript a custom type is really a constructor function).

This will work fine:

app.service(‘myAlertService’, MyAlertService);

The type is defined like this:

function MyAlertService(myAlert) {
this.alert = function (message) {
myAlert.alert(message);
};
}
MyAlertService.$inject = [‘myAlert’];

Notice that this is a constructor function. It also takes on a dependency, only this time I used a different method to annotate the class so Angular knows what to inject. The end result is exactly the same, so your choice of factory or service should be based on your preference for supplying the instance – do you prefer to create classes and pass the constructor function, or would you rather return something explicitly from a factory function? It’s your choice. The service and factory calls wire up the object and refer to how you prefer to make it, not how the app will consume it.

So what about provider? A provider is a special case that allows for configuration. If you don’t need module-wide configuration, go for a service or factory instead. Think of a provider as sitting on top of a service. The provider is an object that can handle configuration. The first time the service itself is needed, Angular will call the $get function on the provider. This will return an instance that is subsequently tracked like any other item that was wired up using a service or factory.

To illustrate, let’s implement the “myAlert” service that was passed into the two previous examples. The service does what you’d expect – it raises an alert – but it can be configured one time only to prepend a date. It will either use the message, or use the combination of the current date and the message. The provider looks like this:

function MyAlertProvider() {
var showTime = false;

    this.setShowTime = function (show) {
showTime = !! show;
};

    this.$get = [‘$window’,

    function ($window) {
return {
alert: function (message) {
var dateStamp = new Date();
if (showTime) {
$window.alert(dateStamp.toString() + “: ” + message);
} else {
$window.alert(message);
}
}
};
}];
}

It contains an internal variable for configuration, exposes a method to configure it, and supplies a $get method to generate the instance (in this case, we’re using the inline annotation to inject the $window service). Note the convention is to take the name you’re going to use for the service and append “Provider” to the end. Here is the set up for the provider. Notice it is named without the provider suffix:

var app = angular.module(‘myApp’, []);
app.provider(‘myAlert’, MyAlertProvider);

And here the module configures it to prepend the date. Notice the dependency requested is for the provider, not the service itself:

app.config([‘myAlertProvider’, function (myAlertProvider) {
myAlertProvider.setShowTime(true);
}]);

Finally I can take all of these items and expose them in a controller like this:

app.controller(‘MyController’, [
‘myAlert’,
‘myAlertService’,
‘myAlertFactory’,
‘$scope’, function (myAlert, myAlertService, myAlertFactory, $scope) {
$scope.alert = function () {
myAlert.alert(“This is an alert!”);
};
$scope.alertService = function () {
myAlertService.alert(“This is an alert!”);
};
$scope.alertFactory = function () {
myAlertFactory.alert(“This is an alert!”);
};
}]);

That’s it. The behavior of the alert calls depends on the one-time configuration of the provider. The service and factory proxies are identical despite the different way they were wired up. If I wanted to make the optional date a parameter and not a configuration option, I would do away with the provider and just use a service or a factory. The full working example is available to you at the following link. Try commenting out the .config call to see the default alert without dates added.

http://jsfiddle.net/jeremylikness/A6Cb2/

Atmosera is an Oregon-based company who architects, deploys, and operates public, private, and hybrid Microsoft Cloud Platform and Azure environments for customers across the globe and diverse industries. Since 2011, Atmosera has been a trusted cloud partner to the State of Oregon. State agencies including the Oregon State Hospital (OSH), Oregon Health Authority (OHA), the Department of Justice, the Department of Human Services, and the Department of Treasury host their applications with Atmosera. This includes a partnership with Enterprise Technology Services (ETS) and the State of Oregon Data Center.

The Right Solution for Your Needs.

We deliver a hybrid spectrum of Microsoft Cloud Platform and Azure solutions to government agencies and application developers who demand a modern, open and flexible cloud service platform. We offer trusted, transparent, and secure Infrastructure as a Service (IaaS) and Platform as a Service (PaaS) solutions for production business applications, Business Intelligence (BI), continuous data protection, application availability, test/development, and Software as a Service (SaaS)

Architected to meet your needs.

Deployed flawlessly.

Operated reliably 24x7x365.

We build solutions to address your individual business objectives with an eye to sustained technology innovation.

We manage the entire lifecycle from 
start to finish to eliminate surprises 
and allow you to focus on your services.

We deploy environments which 
can be managed and maintained for you by our team of experts 24x7x365.

20+ Years of Experience Makes Us a Trusted Partner You Can Count On.

Atmosera backs technology with real humans who deliver experience and unparalleled dedication, resulting in smarter cloud computing investments. We developed a core methodology to ensure we accurately capture your needs and translate them into the best solution possible. This process gives you the peace of mind that your cloud investment will be aligned with the return you seek. We can be counted on to bring our industry experience and real-world best practices to operate Microsoft Cloud Platform and Azure environments.

Assess:

Migrate:

Re-platform:

Operate:

Rely on our team to map your existing environment to a corresponding 
Azure cloud.

Easily move from your existing environment to a public or private Microsoft cloud.

Understand how to transform your applications to better take advantage 
of cloud capabilities.

Our team actively manages all maintenance & optimization to keep your environment running at its best.

Information Security: Protect Your IT with Industry Best Practices.

We provide managed Information Security (InfoSec) and compliance options across the entire computing stack, from connectivity to applications, with stringent physical and logical security controls.

We take on the security and infrastructure concerns by becoming an extension to our customer’s team or their application development vendor. In that partnership, Atmosera shares the responsibility and liability associated with maintaining a secure environment, and stands by that commitment with a guarantee based on the defined lines of responsibility. All Atmosera customers benefit from more than technology by also getting processes, policies, training, and 24x7x365 technical resources. Customers have the peace of mind of knowing an industry expert has performed a thorough risk assessment, identified a remediation plan and provided ongoing audit support to ensure customers stay secure. Best of all, Atmosera understands this level of service is, and will continue to be, required year after year.

Managed Compliance
Stay compliant with IRS-1075, PCI-DSS, HIPAA/HITECH, and HITRUST.
Disaster Recovery (DR) 
& Data Protection
Safeguard your applications and data and stay operational event when disasters strike.
Secure Networks including Firewalls & DDOS Mitigation
Implement networks which deliver better security and usability.

Why Microsoft Cloud Platform and Azure?

Microsoft has made major strides in the public cloud space over the past few years. They are gaining market momentum with companies and also the analysts community who recognize the more than USD15B investment made. At this point Azure has more data centers than AWS and Google Cloud combined. It spans an unparalleled global reach with 36 regions available and more being added. Azure offers companies wanting to put workload in the a public cloud with a secure, scalable and competitive option.

The Power of Microsoft’s Hybrid Cloud Platform.

Microsoft is the only hyperscaler to offer a true hybrid cloud solution with the flexibility to run applications using private or public clouds — and the ability to move between them. Atmosera has the skills and expertise necessary to help architect, deploy, and operate integrated hybrid cloud solutions based on the Microsoft Cloud Platform and microservices. This offers our customers a unique set of capabilities and flexibility when planning out their cloud journey.

Azure Certified for Hybrid Cloud.

Atmosera has developed core competencies and intellectual property to take full advantage of all Azure has to offer. All Atmosera Azure services receive the “Azure Certified for Hybrid Cloud” designation which confirms it passed Microsoft’s rigorous validation process under the Cloud OS Network (COSN) program. Customers benefit from knowing that their solution was carefully planned and executed using best practices and proven methods.

Microsoft Azure Government.

Starting in June of 2017, Microsoft opened up their Microsoft Azure government regions to partners. Atmosera was one of the first Microsoft Cloud Solution Provider (CSP) to be approved to deploy qualified government customers in these dedicated regions.
Azure Government offers world-class security and compliance for US federal, state, local, and tribal government agencies and their partners. It provides an environment for government-only workloads which is operated by screened US citizens. Customers can choose from six data center regions with DoD Impact Level 5 Provisional Authority (PA) including two dedicated regions for US Department of Defense workloads. Environments can leverage hybrid flexibility by maintaining some data and functionality on-premises. Azure Government also offers the most certifications of any cloud provider to simplify critical government compliance requirements.

Azure Government regions where Atmosera can deploy customers include the following six locations:

  • US Gov Virginia
  • US Gov Indiana
  • US Gov Arizona
  • US Gov Texas
  • US DOD East
  • US DOD Central
Atmosera has seen a growing desire to use Azure by government agencies and the availability of Azure Government provides a highly secure and trustworthy cloud where workloads can be deployed and managed. The flexibility of hybrid environments makes it possible to transition workloads to the cloud as slowly or fast as desired by customers. Every deployment includes financially-backed Service Level Agreements or SLAs.

We deliver solutions that accelerate the value of Azure.

Ready to experience the full power of Microsoft Azure?

Start Today

Blog Home

Stay Connected

Upcoming Events

All Events