How to create services in Angular 2

Before starting this article you must have some basic knowledge on Angular 2 , typescript and how  to set up the Angular 2 application.

If you are a newbie to Angular 2 then you can follow my below links . I am sure you will able to write the Angular 2 applications within 5 minutes.

What is typescript ?
http://whymysolutions.blogspot.com/2017/09/what-is-typescript.html

Angular 2 project set up in Visual studio code and a Small Angular 2 application example.

If you are comfortable with basic of Angular 2 then you can directly learn this article step by step.

First we will describe the service creation and then we will use it in a small application.

Step 1 : Create the service file 
   First we will create a file having the name as  mydemoservice.service.ts . Here the *.service.ts* will same but the file name you can change. 

Step 2 :  Import the Injectable member into service file.
 Then import the Injectable memebr from the angular core library . Put the below line top of the service file .

import { Injectable } from '@angular/core';

Step 3 : Declare the Injectable Decorator
 Then declare the Injectable decorator . The decorator precedes with @ symbol and having no semicolon (;) at the end .

  @Injectable()

Step 4 : Export the service class.

import { Injectable } from '@angular/core';
@Injectable()
export class MyDemoService 
{
     // Here we can declare the service property and method as well .

     Method1()
  {
      // Code of the service method
  }

}        

Step 5 : How to consume the service .

    We can consume or import the service into a component or to the app.module.ts .

Step 6 : Import service to a component.

      Import the service class to the top of the component class.

import { Component } from '@angular/core';
import { MyDemoService } from './mydemoservice.service';

Step 7 : Then add the service into providers.

   Add the service member into the providers of the component decorator metadata.

 @Component({
    selector: 'my-app',
    template: '<h2>{{ title }}</h2>',
    providers: [MyDemoService ]
})

Step 8 : Include it through dependency injection .

      In the constructor arguments of the component class, we include it through dependency injection:

constructor(private _myDemoService: MyDemoService ) {
}
  
Step 9 : Now we will use the Service.

   We can user the service property and method by referencing the variable.
ngOnInit() {
        this.title = this._myDemoService.someMethod();
}  

So in this way you can use the services in angular 2 app.
Please share and like this article if it really helped you.

Comments

Post a Comment

Popular posts from this blog

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

The transaction is aborted or Failure while attempting to promote transaction.

Unable to load one or more breakpoints in Visual studio.