Skip to content
Related Articles

Related Articles

AngularJS Services

Improve Article
Save Article
  • Last Updated : 06 Sep, 2022
Improve Article
Save Article

The Services is a function or an object that avails or limitto the application in AngularJS, ie., it is used to create variables/data that can be shared and can be used outside the component in which it is defined. Service facilitates built-in service or can make our own service. The Service can only be used inside the controller if it is defined as a dependency. In the case of many Services, the object that can be utilized, which is defined in DOM already, has few constraints in the AngularJS application. 

Why to use the AngularJS Service?

AngularJS supervise the application constantly. In order to handle the events or any changes in a proper manner, then the Service that is provided by the AngularJS will prefer to use, instead of Javascript Objects. For instance, the window.location object that is that already defined in the DOM, can be used with some limitations, likewise the $location service, in the AngularJS application. For this case, AngularJS generally prefer to use the $location service, instead of using the window.location object.

There are some commonly used built-in services, are described below:

  • $http Service: It makes the request to the server, in order to handle the response by the application.
  • $timeout Service: This service is AngularJS’ version of the window.setTimeout function.
  • $interval Service: This service is AngularJS’ version of the window.setInterval function.

Create the AngularJS Service:

STEP 1: Creating a service will follow the below command:

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 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 capitalized followed by Service written without any space.

STEP 3: So we have to now make changes in service-name.service.ts to create a JSON variable that is supposed to be made available to various components

Sailors = [22, ‘Dustin’, 7];

The 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 the constructor define a property of the Service type

constructor(private demoService: ServiceService) {}

Also, create a 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

Example: This example describes the basic usage of the Services in angularJS.

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


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




<div style="text-align:center; font-family:arial">
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3>AngularJS Servies</h3>
    <h5>{{ message }}</h5>
    <p>ID Name Rating</p>
    <div *ngFor="let m of newData">
        <p>{{ m.id }} {{ m.name }} {{ m.rating }}</p>
    </div>
</div>


app.module.ts




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
  
import { AppComponent } from './app.component';
  
@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
})
export class AppModule { }


Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!