TypeScript, Angular and Factories, Services and Providers

Monday, August 3, 2015

I have been refactoring an Angular project of mine to use TypeScript. I have been doing this for a few reasons:

  • To be able to start using the EcmaScript 6 and beyond coding features.
  • To make it easier to upgrade to Angular 2 in the future.
  • To take advantage of TypeScrip's typing and other features.

One of the issues I have come across while doing this exercise is that all my services are actually Angular Factories.

Angular has three types of services you can have to reuse logic across your application and they are services, factories, and providers.


Factories are typically the most common way to create these components. A factory is basically a function call that returns an object and that object contains properties and functions.


Services are similar to factories except that they are instantiated when you call them. So the functionality you want to reuse you would put the logic on the "this" keyword which is essentially attaching the functionality to the service itself.

When you use a service Angular will automatically call it using the "new" keyword.


Providers are a little more involved, but they are useful when you want to setup some configuration before before you actually call it. It is the only type of service that is available in the "config" section of a module which is executed first, so you can use it at that point to set it up and then call it later in a controller for example.

The problem in TypeScript

Because in TypeScript you create interfaces and then classes that implement those interfaces, factories will not new up your class. So the following will not work in TypeScript.

The code that is generated looks like this:

To get around this issue, I had to "new up" the classes myself before I returned them as a factory. 

The generated JavaScript code now looks like this:

So since this is the case, you might as well start using services rather than factories if you are going to use TypeScirpt, but if you are going to use factories, remember to instantiate them first before you inject them into your code.

comments powered by Disqus