Saturday, December 5, 2015

Creating Services in Angular2.0

In an application,  service is a component which consists of business logic or set of individual functions. Services often served as loosely coupled modules.

If you are building an Angular2.0 application there are various ways to inject the service into your component. Service consumption in Angular2.0 application follows dependency injection principles. Component can be resembled to directives in Angular1.x. So if you component needs a service instance, then the service can be injected while constructing the component.

For example here I am creating a component named as Event component, following is the way the component can be accessed in HTML:


<event-component></event-component>

The Angular2.0 code for the above component written below:

@Component({

    selector: 'event-component',
    templateUrl:'eventcomp.html',
    styles: [],
    directives: []

})

class EventComponent {

  constructor(VenueService:VenueService,

  @Inject('App.config')config: config,food:FoodAndBeveragesService) {

    this.title=config.title;
    this.schedule=config.schedule;
    this.duration=config.duration;
    this.venueServiceInst=VenueService;
    this.booked=false;
    this.beveragesIncluded=food.beveragesIncluded;

  }

  bookVenue(){

    if(this.venueServiceInst.bookVenue()){
      this.booked=true;
    }
  }
}

The constructor in the above code has three services injected into it.


  • VenueService
  • FoodAndBeveragesService
  • config

While bootstrap of your component you can configure services for your component, as written below:


bootstrap(EventComponent,[VenueService,FoodAndBeveragesServiceProvider,
provide('App.config', {useValue:config})]);

The VenueService code is pretty simple, following is the code:


import {Injectable} from 'angular2/angular2';
@Injectable()
export class VenueService{
  bookVenue(){
    console.log('booking venue');
    return true;
  }
}


The above service is written in a separate typescript file. So the export notifies which class you want to expose for access from other files. The Injectable annotation says that the service is injectable.

The FoodAndBeveragesService code is as simple as above service, following is the code:


import {Injectable} from 'angular2/angular2';

@Injectable()
export class FoodAndBeveragesService{

beveragesIncluded:boolean;
  constructor(beveragesIncluded?:boolean){
  this.beveragesIncluded=beveragesIncluded; 
  }

  bookFoodAndBeverages(){

    return true;
  }
}

But while injecting there is a provider configured for it, to create a provider for the service, here is the code snippet for it:

let foodAndBeveragesServiceFactory = () => {
  var beveragesIncluded=true;
  return new FoodAndBeveragesService();
};

let foodAndBeveragesServiceDefinition = {
   useFactory: foodAndBeveragesServiceFactory,
   deps:[]
};

let FoodAndBeveragesServiceProvider = provide(FoodAndBeveragesService, foodAndBeveragesServiceDefinition);
The contrasting difference between the  injection of VenueService and FoodAndBeverageService is the creation of the service instance is in the control of it's corresponding factory method, so in the above factory creation we can change the invocation of the service instance creation as shown in the following code:

let foodAndBeveragesServiceFactory = () => {
  var beveragesIncluded=true;
  return new FoodAndBeveragesService(beveragesIncluded);
};
Now lets come to config service, this is how it's been created:

let config = {

  title: 'AngularJS Meetup',

  schedule:'Mon, 23rd Dec 2015',

  duration:'6'

};
So config is basically an object which can be injected in to any component. To inject it as it's written in the bootstraping of the component:

provide('App.config', {useValue:config})
And while injecting it in the constructor of the component we mention it as follows:

@Inject('App.config')config: config

So above are the ways to create and inject services in Angular2.0. Following is the working code base of the above examples.

No comments:
Write comments