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.

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)

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

   <app-another></app-another>
   <app-servers></app-servers>
<div style="background: palevioletred">
  <p>{{dataService.getValue()}}</p>
</div>
<div style="background: lightgreen">
  <button (click)="dataService.incrementValue()">Increment Value</button>
  <button (click)="dataService.decrementValue()">Decrement Value</button>
</div>

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

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>

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>
  • ng/service.txt
  • Last modified: 2019/11/19 16:54
  • by chongtin