DEV Community

Cover image for AngularJS Factory Vs Service Vs Provider
Marc West
Marc West

Posted on

AngularJS Factory Vs Service Vs Provider

AngularJS is a JavaScript based framework used to design single-page component-based web apps. For beginners, such as myself, it can be a little confusing as to what logic and data should be put in the controller, or what service should be used instead. Typically controllers should not be full of persistent because they are instantiated only when needed and then discarded. That just leaves the many service methods you have to choose from.

Factories

Factories are the most frequently used method for registering a service. The reason for that being that they are easier to write and use, and your business logic and other data is never exposed to the rest of the app. The factory method takes two parameters: the string you want to name the factory, and the factory function which will declare and return the object. Any properties attached to the new object will then be available to other parts of the app through a controller. Because the service is wrapped in an instance of an object, the internal logic and data remains unexposed.

Service

Very similar to the factory is the service. The main difference between the two is that the service method uses a constructor function to register the service. Services are instantiated in AngularJS with the 'new' keyword, which means properties are added using the 'this' keyword, and the service constructor returns 'this'. When passed through to the controller, the properties on 'this' will be available in that part of your app, but, because of this all of the internal logic of a given service is exposed to the rest of the app.

Providers

Providers also do basically the same thing, but with a little more work involved and a few bonus features. Providers are the only service that can be passed directly into the .config() function. This allows alterations to be made to portions of the service before it is made available to the rest of the app. Also the only properties on the provider that will be available to the controller will be the ones assigned to this.$get. This allows the programmer to keep internal logic hidden or exposed as they see fit.

This is just a brief rundown of a few service methods available to you in AgularJS, and there's obviously a lot more detail involved, but this should help clear up some of the uses. You will probably want to use a factory most of the time, use a service for simpler logic, and use a provider when you need more customization options.

Top comments (0)