Angularにおけるあるサービスから別のサービスへの注入
プロジェクトの作業において、機能を拡張するために、 あるサービスから別のサービスへ注入が必要になる場合があります。 新しいデータが追加されたときにコンソールにメッセージを出力する、 別のサービスを作成してみましょう。
最初に、フォルダ test/src/app 内に
ファイル log.service.ts を作成します。
クラス LogService をエクスポートし、
コンソールにメッセージを出力するための
関数 write を記述します:
import { Injectable } from '@angular/core';
@Injectable()
export class LogService {
write(message: string) {
console.log(message);
}
}
次に、私たちのサービス DataService に移動し、
新しいサービスをインポート、インジェクト、使用します:
import { 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('データを取得しました'); // 使用
return this.data;
}
addData(name: string){
this.data.push(name);
this.logService.write('新しい要素が追加されました'); // 使用
}
}
しかし、これだけでは不十分です。 コンポーネントクラスでも新しいサービスを宣言する必要があります。 直接的には使用されていませんが:
import { Component } from '@angular/core';
import {DataService} from './data.service';
import {LogService} from './log.service'; // インポート
@Component({
........
providers: [DataService, LogService] // 追加
})