Services in Angular 8

This project will demonstrate how to Create Services in Angular 8

  • Angular8
    • src
      • app
        • services
          • math.service.ts
        • app.component.html
        • app.component.ts
        • app.module.ts
import { Injectable } from '@angular/core';

@Injectable()
export class MathService {

    addition(a: number, b: number): number {
        return a + b;
    }

    subtraction(a: number, b: number): number {
        return a - b;
    }

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

}
Result 1: {{result1}}
<br>
Result 2: {{result2}}
<br>
Result 3: {{result3}}
import { Component, OnInit } from '@angular/core';

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

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

export class AppComponent implements OnInit {

    result1: number;
    result2: number;
    result3: number;

    constructor(
        private mathService: MathService
    ) { }

    ngOnInit() {
        this.result1 = this.mathService.addition(10, 2);
        this.result2 = this.mathService.subtraction(10, 2);
        this.result3 = this.mathService.multiply(10, 2);
    }

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

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

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

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

export class AppModule { }

Screenshots