Example: Cleaning Up Signal Effects
Let's consider a scenario where you have a signal that fetches user data, and you want to clean up the effect when the component is destroyed.
Step 1: Setting Up Signals
First, set up a basic signal for user data.
typescriptimport { signal } from '@angular/core';
// Signal to hold user data
const userDataSignal = signal<UserData | null>(null);
Step 2: Creating an Effect
Create an effect that reacts to changes in the userDataSignal
. This effect might make an API call to fetch user details.
typescriptimport { effect } from '@angular/core';
const fetchUserDataEffect = effect(() => {
const userId = userIdSignal(); // Assume userIdSignal exists
if (userId) {
fetchUserData(userId).then(userData => {
userDataSignal.set(userData);
});
}
});
Step 3: Cleaning Up the Effect
To clean up the effect manually, you can return a cleanup function from the effect. This is typically done in the ngOnDestroy
lifecycle method of the component.
typescriptimport { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-user',
template: `<div>{{ userDataSignal() | json }}</div>`
})
export class UserComponent implements OnDestroy {
constructor() {
// Setup the effect
fetchUserDataEffect();
}
ngOnDestroy() {
// Cleanup the effect
fetchUserDataEffect.cleanup();
}
}
Summary
- Setup Signal: Define your signal to hold data.
- Create Effect: Use the effect function to reactively fetch data.
- Cleanup: In
ngOnDestroy
, call the cleanup method to avoid memory leaks.
By following this approach, you can manage signals and their effects more efficiently, ensuring that resources are freed when they are no longer needed.
No comments:
Post a Comment