Back to articles
Stop Writing .subscribe() in Angular Components — Use toSignal Instead

Stop Writing .subscribe() in Angular Components — Use toSignal Instead

via Dev.to WebdevDominik Paszek

If you've been writing Angular for more than a week, you know this pattern by heart: protected userData = signal < UserData | undefined > ( undefined ); ngOnInit () { this . userService . getUserData () . pipe ( tap ( data => this . userData . set ( data )), takeUntilDestroyed ( this . destroyRef ) ) . subscribe (); } Signal. Subscribe. tap. set. Cleanup. Every. Single. Time. It works, but there's a lot of moving parts for something that boils down to "I want to show this data in my template." Turns out Angular has a one-liner for exactly this — toSignal . The core idea Observables and Signals live in different worlds. Observables are async — they emit values over time, can be cold or hot, and can stay silent for a while. Signals are synchronous — they always have a current value and work directly in templates without any pipe magic. toSignal is the bridge. You hand it an Observable, it gives you back a Signal that: subscribes automatically updates on every emission cleans itself up wh

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
1 views

Related Articles