Services In Angular 2

Table of contents
Reading Time: 2 minutes

Services are the building blocks that Angular provides for the definition of the business logic of our applications. In AngularJs 1.x, we had three different ways for defining services:

// The Factory method
module.factory('ServiceName', function (dep1, dep2, …) {
  return {
    // public API
  };
});

// The Service method
module.service('ServiceName', function (dep1, dep2, …) {
  // public API
  this.publicProp = val;
});

// The Provider method
module.provider('ServiceName', function () {
  return {
    $get: function (dep1, dep2, …) {
      return {
        // public API
      };
    }
  };
});

Although the first two syntactical variations provide similar functionality, they differ in the way the registered directive will be instantiated. The third syntax allows further configuration of the registered provider during configuration time.

Having three different methods for defining services is quite confusing for the AngularJS 1.x beginners.

When a given service is required, through the DI mechanism of the framework, AngularJS resolves all of its dependencies and instantiates it by passing them to the factory function, which encapsulates the logic for its creation. The factory function is passed as the second argument to the factory and service methods. The provider method allows definition of a service on lower level; the factory method there is the one under the$get property of the provider.

Just like AngularJS 1.x, Angular 2 tolerates this separation of concerns as well

in Angular 2 we use injectable services

This is a component that wishes to use injectable service needs to receive it in one of its constructor’s parameters. Having the private keyword before each injectable parameter makes a class member named the same as the parameter name and assigns the parameter to it.

The code example below demonstrates how to declare an injectable service and how to use it.

@Injectable()
export class MyService {
items:Array<any>;
constructor() {
this.items = [
{name: 'Christoph Burgdorf', degree: 'mca'},
{name: 'Pascal Precht', degree: 'mca'},
]
}
getNames() {
return this.items
}
}

As you can see above, this is simply an exported class decorated with the Injectable decorator.

Second, let’s use it in a component:

import {MyService} from 'path/to/myService'

Second, we need to instansiate it. The Angular 2.0 framework will do that for us after we will put our service in a component’s providers array.

Providers: Having the constructor parameters doesn’t make sure that in instance will be sent to the constructor. To make sure in instance is created, we need to put the injectable service type in the providers array of theViewMetaData

@Component({ /*some ViewMetaData members */
   providers: [ MyService],
   /*some other ViewMetaData members */ });

And, last but not least, we have to inject the service in our component’s class constructor.

export class MyCompoentClass {
newItems:Array<any>;
 constructor(nameservice:MyService) {
this.newitems = nameservice.getNames();
}
}

KNOLDUS-advt-sticker

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading