AngularJS | Services - GeeksforGeeks

21 May, 2019
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-names 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.
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.
STEP #2: After the service is created, we have to include it in the providers of app.module.tsproviders: [Service-nameService],here, the first letter of the service-name should be capital followed by Service written without any space.
here, the first letter of the service-name should be capital followed by Service written without any space.
STEP #3: So we have to now make changes in service-name.service.ts create a json variable which is supposed to be made available to various componentsSailors = [22, ‘Dustin’, 7];Sailors variable here is an array.
STEP #4: In app.component.ts make the following changes:import the service among the rest of the required importsExample:-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 typeIn constructor define a property of the Service typeconstructor(private demoService: ServiceService) {}Also create an ngOnInit method:    ngOnInit(): void {
    this.newData=this.demoService.Sailors;

import { Service-nameService } from './service-name.service';
just like the way we did it in providers.
constructor(private demoService: ServiceService) {}
    ngOnInit(): void {
    this.newData=this.demoService.Sailors;

STEP #5: In app.component.html we will print the data stored in newData :{{newData}}Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.tsSyntax (Example #1):serice.service.tsimport { 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.tsimport { 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-TutorialMy Personal Notes
arrow_drop_upSave
{{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
Picked
AngularJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
Angular PrimeNG Calendar Component
What is AOT and JIT Compiler in Angular ?
How to set focus on input field automatically on page load in AngularJS ?
Angular 10 (blur) Event
Angular PrimeNG Messages Component