Services are used to create variables/data that can be shared and can be used outside the component in which it is defined.
- STEP #1: Creating a service:-
ng g s service-name
s is a short-form for service.This creates two files service-name.service.spec.ts which is not supposed to be changed and a service-name.service.ts.
- providers: [Service-nameService],
here, the first letter of the service-name should be capital followed by Service written without any space.
-
Sailors = [22, ‘Dustin’, 7];
Sailors variable here is an array.
- import the service among the rest of the required imports
Example:-
import { Service-nameService } from './service-name.service';
just like the way we did it in providers.
-
Create a variable of any type: newData without mentioning any type
-
In constructor define a property of the Service type
constructor(private demoService: ServiceService) {}
-
Also create an ngOnInit method:
ngOnInit(): void { this.newData=this.demoService.Sailors;
{{newData}}
Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.ts
Syntax (Example #1):
serice.service.ts
import { Injectable } from '@angular/core' ; @Injectable({ providedIn: 'root' }) export class ServiceService { Sailors = [ { id: 22, name: 'Dustin' , rating: 7 }, { id: 29, name: 'Brutus' , rating: 1 }, { id: 31, name: 'Lubber' , rating: 8 }, { id: 32, name: 'Andy' , rating: 8 }, { id: 58, name: 'Rusty' , rating: 10 }, { id: 64, name: 'Horatio' , rating: 7 }, { id: 71, name: 'Zorba' , rating: 10 }, { id: 74, name: 'Horatio' , rating: 9 } ]; constructor() { } getData() { return 'This is the list of sailors and their corresponding ratings' ; } } |
In app.component.ts
import { Component } from '@angular/core' ; import { ServiceService } from './service.service' ; @Component({ selector: 'app-root' , templateUrl: './app.component.html' , styleUrls: [ './app.component.css' ] }) export class AppComponent { newData; message:string= '' ; constructor(private demoService: ServiceService) {} ngOnInit(): void { this .newData= this .demoService.Sailors; this .message= this .demoService.getData(); } } |
app.component.html
< b >Service Example</ b > < h5 >{{ message }}</ h5 > < p > ID Name Rating</ p > < div * ngFor = "let m of newData;" > < p >{{m.id}} {{m.name}} {{m.rating}}</ p > </ div > |
Output:
References:
https://coursetro.com/posts/code/61/Angular-4-Services-Tutorial