user2202911 user2202911 - 3 months ago 21x
AngularJS Question

What is the equivalent of a factory in Angular2?

So I am used to using factories & services in Angular.

I am reading through the Angular2 docs and I don't see any equivalent of a factory. What is the equivalent for Angular2?


Factories, services, constants and values are all gone in Angular2. Angular2 is radically and fundamentally different from the classic Angular. In Angular2, the core concepts are

  • components
  • dependency injection
  • binding

The idea of services, factories, providers and constants has been criticized in Angular 1. It was difficult to choose between one. Removing them simplifies things a bit.

In the original Angular, you would define a service like so

app.service('BookService', ['$http', '$q', BookService]);
function BookService($http, $q){
  var self = this;
  var cachedBooks;
  self.getBooks = function(){
    if (cachedBooks) {
      return $q.when(cachedBooks);
    return $http.get('/books').then(function(response){
      cachedBooks =;
      return cachedBooks;

Angular2 significantly leverages ES6 syntax to make the code more readable and easier to understand.

One new keyword in ES6 is class, which can be thought of as a service.

ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

Here's how that same code might look in Angular2

import {HttpService, Promise}  from '../Angular/Angular2';
export class BookService{
    $http, $q, cachedBooks;
    constructor($http: HttpService, $q: Promise) {
        this.$http = $http;
        this.$q = $q
    getBooks() {
    if (this.cachedBooks) {
        return this.$q.when(this.cachedBooks);
    return this.$http.get('/books').then(function(data) {
        this.cachedBooks = data.books;
        return this.cachedBooks;