Table of Contents

Service

Angular services can be called by different component in your project through Angular dependency injection. If we use Angualt dependency injection, services are singleton, meaning that every component that use the service is using the same instance.

You can out HTTP request, general function call, or storage variables for cross component communication. In this example, we will create a service called data, and use it for two different components (servers, another) that display on the same view.

The another component display a value, and the servers component control the value. Our data service will work in between them. To make this example simple to read, we do not have any logic in our component ts files except the dependency injection in the constructor part.

Create the Service in CLI

we can use ng generate service serviceName to create a service. Here is how we create our data service. Two files will be generated, we do only care about data.service.ts for now.

ng generate service data
CREATE src/app/data.service.spec.ts (323 bytes)
CREATE src/app/data.service.ts (133 bytes)

app.component.html

in the root HTML component, we add our another and servers components.

   <app-another></app-another>
   <app-servers></app-servers>

antoher.component.html

<div style="background: palevioletred">
  <p>{{dataService.getValue()}}</p>
</div>

services.component.ts

<div style="background: lightgreen">
  <button (click)="dataService.incrementValue()">Increment Value</button>
  <button (click)="dataService.decrementValue()">Decrement Value</button>
</div>

servers.component.ts, antoher.component.ts

The important part here is import {DataService} from “../data.service”; and constructor(private dataService: DataService) {…}. For antoher.component.ts, we do the similar thing.

import {Component, OnInit} from '@angular/core';
import {DataService} from "../data.service";

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {

  constructor(private dataService: DataService) {
  }

  ngOnInit() {
  }
}

antoher.component.html

We user this to display the value that store in our data service. Note that we have used dependency injection in our ts file, we can access the service directly like an object in the HTML view by using ng.

<div style="background: palevioletred">
  <p>{{dataService.getValue()}}</p>
</div>

servers.component.html

We user this component to display two buttons control for the values. We can bind the function like this. Since we are using the same service. When we update the value in the service, Angular detected it, and will update any view that using this value.

<div style="background: lightgreen">
  <button (click)="dataService.incrementValue()">Increment Value</button>
  <button (click)="dataService.decrementValue()">Decrement Value</button>
</div>