AngularJS | Services

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
      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;
      
  • 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.ts

    Syntax (Example #1):
    serice.service.ts

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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';
      }
    }

    chevron_right

    
    

    In app.component.ts

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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();
      }
    }

    chevron_right

    
    

    app.component.html

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <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>

    chevron_right

    
    

    Output:
    service

    References:
    https://coursetro.com/posts/code/61/Angular-4-Services-Tutorial



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.