Skip to content
Related Articles

Related Articles

AngularJS | Services

View Discussion
Improve Article
Save Article
  • Last Updated : 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-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.ts
      providers: [Service-nameService],

    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 components
      Sailors = [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 imports

      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 {
  • STEP #5: In app.component.html we will print the data stored in newData :
  • Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.ts

    Syntax (Example #1):

    import { Injectable } from '@angular/core';
      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';
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    export class AppComponent {
      constructor(private demoService: ServiceService) {}
      ngOnInit(): void {



    <b>Service Example</b>
    <h5>{{ message }}</h5>
    <p> ID Name Rating</p>
    <div *ngFor="let m of newData;">
        <p>{{}} {{}} {{m.rating}}</p>




    My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!