Injecting one service into another in Angular
To work on a project, we may need to embed one service into another to extend their functionality. Let's make another service that will output messages to the console when new data is added.
First, in the test/src/app folder, create the log.service.ts file. Export the LogService class, in which we write the write function to output a message to the console:
import { Injectable } from '@angular/core';
@Injectable()
export class LogService {
write(message: string) {
console.log(message);
}
}
Next, we go to our service DataService and import, inject and use our new service:
import { Injectable } from '@angular/core';
import { LogService } from './log.service'; // we import
@Injectable()
export class DataService {
private data: string[] = ['a', 'b', 'c'];
constructor(private logService: LogService) { // we inject
}
getData(): string[] {
this.logService.write('data received'); // use return this.data;
}
addData(name: string){
this.data.push(name);
this.logService.write('new elem added'); // we use
}
}
This, however, is not enough. You also need to register a new service in the component class, although it is not directly used there:
import { Component } from '@angular/core';
import {DataService} from './data.service';
import {LogService} from './log.service'; // we import
@Component({
........
providers: [DataService, LogService] // we add
})