How To Get Data Using Angular Services

INTRODUCTION

To get data from an external source (DATABASE or SOME FILE) dynamically, we need some tools or we can say, some helpers that help us to get the data. These are called SERVICE.

SERVICE

First, we will understand what 'Service' is.  Basically, it means an element that provides something. Similarly, in the case of ANGULAR, if we want to get data from any source, we use services.

FUNCTIONALITY

  1. If we talk about AngularJS, in this, we have five ways to create service, but in Angular 2, we just have one way or single service. That is good because we will not confuse them.
  2. This data is returned in the form of ‘PROMISES’ or ‘OBSERVABLE’ .
  3. This SERVICE is decorated with @injectable .
  4. Then use export service class to achieve it.

SYNTAX

  1. //Import from ‘@angular/core';’ to decorate @injectable  
  2. Import {  
  3.     injectable  
  4. }  
  5. from‘ @angular / core ';’  
  6. @injectable()  
  7. Export class serviceclass {} 

 

STEP 1 - Create 'ServiceClass.ts' file in your solution.

  1. The Injectable decorator is imported from the angular/core module.
  2. In this class I use decorator @Injectable that allows functionality of this class to be injected.
  3. Create export class with name ServiceClass.

     
Step 2

Create 'Service.Component.ts' class or you can add code to your component,
  1. First I import component and ServiceClass
  2. Then to decorate class I use component.
  3. In Component, first, I use ‘SELECTOR’ through which we load our HTML.
  4. Then I use ‘TEMPLATEURL’ which is used as HTML URL ( I will discuss this later.)
  5. Then ‘provides’ which helps to get service.
  6. Then export class through which we do our logic.

In the constructor, we define a variable called _service of the type ServiceClasss so that it can be called anywhere.

 

Step 3

Create Service.html which will contain the following.

 
 
Step 4

Output

 

Thanks for reading.