Using Signals to Update Data in Angular 18: A Comparison with RxJS
文章目錄
A new feature called signals has emerged in Angular, offering a cleaner and more intuitive approach to state management compared to the traditional RxJS-based methods. In this post, we’ll compare the use of RxJS with signal() for managing data updates, specifically focusing on updating user information upon login or logout.
The following example uses the @let
syntax, which was introduced in Angular 18.
Using RxJS to Update Data
1. Define the Subject
To manage user data with RxJS, we often define a BehaviorSubject
that will hold and emit the user data.
_user: BehaviorSubject<User | null> = BehaviorSubject<User | null>(null);
user$ = this._user.asObservable();
2. Set the Value
Use the next()
method to update the value of user$
.
const user = new User();
this.user$.next(user);
3. Get the Value
In HTML templates, you can use the async
pipe to unwraps user$
observable and retrieve its value.
@let user = user$ | async
@if(user) {
<p>{{ user.id }}{{ user.name }}</p>
}
Using Signals to Update Data
1. Define the Signal
Instead of BehaviorSubject
, we now define a WritableSignal
using the signal()
function.
user$: WritableSignal<User | null> = signal(null);
2. Set the Value
You can use the set()
method to update the value of the signal.
const user = new User();
this.user$.set(user);
3. Get the Value in HTML templates
You can only access the signal’s value in Angular templates with the ()
syntax after the variable name.
@let user = user$()
@if(user) {
<p>{{ user.id }}{{ user.name }}</p>
}
Conclusion
With Angular’s new signal API, managing user data becomes more streamlined, reducing the need for explicit subscriptions and unsubscriptions common in RxJS. Whether you prefer the flexibility of RxJS or the simplicity of signals, both approaches will allow you to efficiently handle state updates in your Angular application. The introduction of signals provides a more modern, intuitive way to manage data flows, making your code more readable and maintainable.