Creating a Logging Service in Angular

logging2.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class Logging2Service {

  constructor() {
  }

  logStatus(status: string) {
    console.log('Status : ' + status);
  }
}

app.component.ts

import {Component} from '@angular/core';
import {Logging2Service} from './logging2.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [Logging2Service]
})
export class AppComponent {

  constructor(private loggingService: Logging2Service) {
  }

  onButtonClick() {
    this.loggingService.logStatus('New');
  }
}

app.component.html

<input type="button" (click)="onButtonClick()" value="Log"/>

Above we injected the service to component level so we can have different instances of service for different components, but we can have the service on app level by initializing it in app.module.ts (we should remove it from component providers). On this case, all instances of service in the application share the same data.

app.module.ts

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

import { AppComponent } from './app.component';
import {Logging2Service} from './logging2.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [Logging2Service],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Reference
https://github.com/mhdr/AngularSamples/tree/master/019/my-app
https://angular.io/guide/hierarchical-dependency-injection
https://itnext.io/understanding-provider-scope-in-angular-4c2589de5bc