サービスは、非UI ロジック(データ取得、ビジネスルール、共有状態、ロギング)を担当するクラスで、複数のコンポーネントから再利用できます。**依存性注入(DI)**は、コンポーネントが手動で作成する代わりに、Angular が必要なコンポーネントにサービスを提供する仕組みです。
サービスの定義
ts
{ } ;
({ : })
{
users = [];
() { .; }
() { ..(u); }
}
@Injectable({ providedIn: "root" }) デコレーターは、サービスを Angular の DI システムに登録し、アプリケーション全体で使用される単一の共有インスタンス(シングルトン)として機能します。
@Component({ ... })
export class UserListComponent {
// Angular sees this constructor param and INJECTS the singleton automatically
constructor(private userService: UserService) {}
users = this.userService.getUsers(); // just use it
}
サービスをコンストラクターパラメーターとして宣言するだけで、Angular の DI がインスタンスを作成して提供します。new UserService() と記述することはありません。(モダン Angular ではコンストラクターインジェクションの代わりに inject() 関数を使用することもできます。)
import { inject } from "@angular/core";
export class UserListComponent {
private userService = inject(UserService); // alternative injection style
}
✓ Single source of truth — one shared UserService instance across components
✓ Loose coupling — components depend on the type, not on constructing it
✓ Testability — swap in a mock service in tests easily
✓ Lifecycle management — Angular handles creation and sharing
コンポーネントが依存関係を構築しないため、テストでモックサービスをインジェクションしたり、実装をアプリケーション全体の1箇所で変更したりできます。
サービス + DI は Angular アーキテクチャの中核です。コンポーネントは UI に専念し、サービスはロジックと状態を保持し、DI が最小限の結合度で それらを接続します。
このような分離(そして それがもたらすテスト可能性)は Angular の特徴であり、バックエンドフレームワークから借用されています。@Injectable({ providedIn: 'root' }) は、共有可能でインジェクション可能なシングルトンの日常的なパターンです。