Call A Service from Another Service in Angular 6


Create new folder named learnangular5withrealapps and select to this folder in Visual Studio Code

Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6




Create new folder, named services in src\app folder. Create services as below

In services folder, create new TypeScript file, named math.service.ts contains math operators

import { Injectable } from '@angular/core';

@Injectable()
export class MathService {

	multiply(a: number, b: number): number {
		return a * b;
	}

}

In services folder, create new TypeScript file, named calculator.service.ts. This service will call math service

import { Injectable } from '@angular/core';

import { MathService } from './math.service';

@Injectable()
export class CalculatorService {

	constructor(
		private mathService: MathService
	) { }

	square(a: number): number {
		return this.mathService.multiply(a, a);
	}

	cube(a: number): number {
		return this.mathService.multiply(a, this.mathService.multiply(a, a));
	}

}




Create new TypeScript file, named app.component.ts in src\app folder. In this component will call methods in calculator service

import { Component, OnInit } from '@angular/core';
import { CalculatorService } from './services/calculator.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

  result1: number;
  result2: number;

  constructor(
    private calculatorService: CalculatorService
  ) { }

  ngOnInit() {
    this.result1 = this.calculatorService.square(2);
    this.result2 = this.calculatorService.cube(3);
  }

}

Create new file, named app.component.html in src\app folder. In this view, show values from component

Result 1: {{result1}}
<br/>
Result 2: {{result2}}

In app.module.ts file in src\app folder. Add new component and new services to module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { MathService } from './services/math.service';
import { CalculatorService } from './services/calculator.service';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [
    MathService,
    CalculatorService
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }




In Terminal windows in Visual Studio Code and type: ng serve –open, program will open url http://localhost:4200/ on browser

Result 1: 4
Result 2: 27

I recommend you refer to the books below to learn more about the knowledge in this article: