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
- 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.
- This data is returned in the form of ‘PROMISES’ or ‘OBSERVABLE’ .
- This SERVICE is decorated with @injectable .
- Then use export service class to achieve it.
SYNTAX
-
- Import {
- injectable
- }
- from‘ @angular / core ';’
- @injectable()
- Export class serviceclass {}
STEP 1 - Create 'ServiceClass.ts' file in your solution.
- The Injectable decorator is imported from the angular/core module.
- In this class I use decorator @Injectable that allows functionality of this class to be injected.
- Create export class with name ServiceClass.
Step 2
Create 'Service.Component.ts' class or you can add code to your component,
- First I import component and ServiceClass
- Then to decorate class I use component.
- In Component, first, I use ‘SELECTOR’ through which we load our HTML.
- Then I use ‘TEMPLATEURL’ which is used as HTML URL ( I will discuss this later.)
- Then ‘provides’ which helps to get service.
- 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.