การนำบริการหนึ่งเข้ามาในอีกรายการหนึ่งใน Angular

สำหรับการทำงานในโครงการ เราอาจจำเป็นต้อง นำบริการหนึ่งเข้ามาใช้อีกรายการหนึ่งเพื่อ เพิ่มขีดความสามารถของพวกมัน มาลองสร้าง บริการอีกตัวหนึ่งที่จะแสดงข้อความ ในคอนโซลเมื่อมีการเพิ่มข้อมูลใหม่กัน

เริ่มแรก ในโฟลเดอร์ test/src/app สร้าง ไฟล์ log.service.ts ส่งออกคลาส LogService ซึ่งเราจะเขียนฟังก์ชัน write สำหรับแสดงข้อความ ในคอนโซล:

log.service.tsimport { Injectable } from '@angular/core';

@Injectable()
export class LogService {
  write(message: string) {
    console.log(message);
  }
}

ต่อมา ไปที่บริการของเรา DataService และนำเข้า, อินเจกต์, และใช้งาน บริการใหม่ของเรา:

app/data.service.tsimport { Injectable } from '@angular/core';
import { LogService } from './log.service'; // นำเข้า

@Injectable()
export class DataService {
  private data: string[] = ['a', 'b', 'c'];
  
  constructor(private logService: LogService) { // อินเจกต์
    
  }
  
  getData(): string[] {
    this.logService.write('data received'); // ใช้งาน
    return this.data;
  }
  
  addData(name: string){
    this.data.push(name);
    this.logService.write('new elem added'); // ใช้งาน
  }
}

แต่เพียงเท่านี้ยังไม่พอ ยังจำเป็นต้องระบุ บริการใหม่ในคลาสของคอมโพเนนต์ด้วย แม้ว่า จะไม่ได้ใช้งานโดยตรงที่นั่น:

app/app.component.tsimport { Component } from '@angular/core';
import {DataService} from './data.service';
import {LogService} from './log.service'; // นำเข้า

@Component({
  ........
  providers: [DataService, LogService] // เพิ่ม
})