ANGULAR

Angular入門ガイド:コンポーネント・DI・RxJSで始めるエンタープライズアプリ

AngularはGoogleが開発・メンテナンスするTypeScriptベースのフルフレームワークです。ルーティング、状態管理、HTTPクライアント、フォーム処理まですべてを内蔵し、大規模エンタープライズアプリ開発に最適化されています。

Angularの核心哲学

ReactやVueとは異なり、Angularはオピニオネイテッドなフルフレームワークです。構造とパターンが明確に定められており、チーム規模が大きくなっても一貫したコードスタイルを維持できます。

  • TypeScriptネイティブ:型安全性とIDEサポート
  • 依存性注入(DI):テスト容易性とモジュール化
  • RxJS統合:非同期データストリーム処理
  • SSRサポート:Angular UniversalによるサーバーサイドレンダリングSSR

コンポーネント(Component)

Angularアプリの基本的な構成要素です。テンプレート、スタイル、ロジックを一つの単位としてカプセル化します。

import { Component, signal, computed } from '@angular/core';

@Component({
  selector: 'app-counter',
  standalone: true,
  template: `
    <div class="counter">
      <p>現在のカウント: {{ count() }}</p>
      <p>2倍: {{ doubled() }}</p>
      <button (click)="increment()">+1</button>
      <button (click)="decrement()">-1</button>
    </div>
  `,
})
export class CounterComponent {
  count = signal(0);
  doubled = computed(() => this.count() * 2);

  increment() { this.count.update(v => v + 1); }
  decrement() { this.count.update(v => v - 1); }
}

依存性注入(Dependency Injection)

AngularのDIシステムはサービスのインスタンスをコンポーネントに自動的に提供します。テスト時にはモックオブジェクトに簡単に差し替えられるため、ユニットテストが非常に容易です。

import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class PostService {
  private readonly http = inject(HttpClient);

  getPosts(): Observable<Post[]> {
    return this.http.get<Post[]>('/api/posts');
  }
}

@Component({ ... })
export class PostListComponent {
  private readonly postService = inject(PostService);
  posts = signal<Post[]>([]);

  ngOnInit() {
    this.postService.getPosts().subscribe(posts => this.posts.set(posts));
  }
}

RxJSとリアクティブプログラミング

Angularは非同期処理のためRxJS Observableを積極的に活用します。複数の非同期ストリームを宣言的に組み合わせる強力なパターンを提供します。

import { combineLatest } from 'rxjs';
import { map, debounceTime, switchMap } from 'rxjs/operators';

combineLatest([searchQuery$, filterCategory$])
  .pipe(
    debounceTime(300),
    switchMap(([query, category]) =>
      this.postService.search(query, category)
    ),
    map(results => results.filter(p => p.published))
  )
  .subscribe(posts => this.posts.set(posts));

SSRと段階的ハイドレーション

Angular 17+からprovideClientHydration(withEventReplay())によりサーバーでレンダリングされたHTMLをクライアントで再利用します。これによりFCP(First Contentful Paint)を大幅に改善できます。

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(withFetch()),
    provideClientHydration(withEventReplay()),
  ],
};
F

Fit System

10年以上のソフトウェアエンジニアリング経験を持つ開発者です。高性能システム設計とクラウドネイティブアーキテクチャを専門としています。