Angular 19.2で、HTTPリソースとレスポンスストリーミングが実験的に登場!
Angular 19.2がリリースされました!今回の目玉は、HTTPリソースとレスポンスストリーミングの実験的機能です。Signalベースの開発がますます便利になっていくのを感じますね。
HTTPリソースで、非同期処理がもっとシンプルに
Angular v19で実験的に再リリースされたHTTPリソース、めちゃくちゃ便利です。これまでの非同期処理の状態管理(ローディング中、成功、エラー)が、Signalベースで超シンプルに書けるようになりました。
例えば、ユーザープロフィールを表示するコンポーネントを考えてみましょう。従来の書き方だと:
@Component({
selector: 'app-user-profile',
template: `
<div *ngIf="loading">Loading...</div>
<div *ngIf="error">{{ error }}</div>
<div *ngIf="user">
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
</div>
`
})
export class UserProfileComponent implements OnInit {
user: User | null = null;
loading = false;
error: string | null = null;
private http = inject(HttpClient);
constructor() {}
ngOnInit() {
this.loading = true;
this.http.get<User>('/api/user').pipe(
finalize(() => this.loading = false)
).subscribe({
next: (user) => this.user = user,
error: (err) => this.error = err.message
});
}
}
これが、HTTPリソースを使うと:
@Component({
selector: 'app-user-profile',
template: `
<div *ngIf="userResource.isLoading">Loading...</div>
<div *ngIf="userResource.error">{{ userResource.error }}</div>
<div *ngIf="userResource.hasValue">
<h2>{{ userResource.value.name }}</h2>
<p>{{ userResource.value.email }}</p>
</div>
`
})
export class UserProfileComponent {
userResource = httpResource(inject(HttpClient).get<User>('/api/user'));
}
めちゃくちゃシンプルになりました!isLoading
やhasValue
などのプロパティがSignalとして提供されるので、テンプレートでの状態管理が超楽です。
レスポンスストリーミングで、リアルタイムデータをスマートに処理
もう一つの実験的機能、レスポンスストリーミングもかなり期待できます。チャットアプリとか、リアルタイムでデータが更新されるようなアプリケーションで活躍しそうです。
例えば、チャットアプリのメッセージ表示を考えてみましょう:
@Component({
selector: 'app-chat',
template: `
<div class="messages">
<div *ngFor="let message of messagesResource.value">
<div class="message">{{ message.text }}</div>
</div>
</div>
<div *ngIf="messagesResource.isLoading">メッセージを読み込み中...</div>
`
})
export class ChatComponent {
messagesResource = rxResource(
inject(ChatService).getMessageStream()
);
}
これまでのように、Observableをsubscribeして状態管理する必要がなくなりました。Signalベースで、より宣言的に書けるようになりましたね。
テンプレートリテラル式もサポート
Angular 19.2では、テンプレート内での開発体験も向上しています。Untagged template literal expressionsのサポートにより、テンプレート内での式の記述がより直感的になりました。
従来の書き方:
<div>{{ (user$ | async)?.name }} さんの残高: {{ (balance$ | async) | currency }}</div>
新しい書き方:
<div>${(user$ | async)?.name} さんの残高: ${(balance$ | async) | currency}</div>
個人的には、この機能はまだ実験的な段階なので、本番環境での使用はもう少し様子を見たいところです。でも、将来的にはかなり便利になりそうな予感がします!
まとめ
Angular 19.2の新機能、特にHTTPリソースはかなり実用的で、早く安定版になってほしいなと思っています。Signalベースの開発がますます進化していくのを感じますね。
これらの機能について、Angularチームは開発者からのフィードバックを積極的に求めています。GitHubのRFCをチェックして、意見を共有してみるのもいいかもしれません。
それでは、また!
Discussion