पाठ 26 / 30

computed() और effect()

सिग्नल से मान निकालें और उनके बदलने पर साइड इफ़ेक्ट चलाएँ।

computed()

computed(), दूसरे सिग्नलों से एक रीड-ओनली सिग्नल निकालता है — यह केवल तब अपने-आप दोबारा गणना करता है जब कोई निर्भरता बदले।

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

export class CartComponent {
  price = signal(250);
  quantity = signal(2);
  total = computed(() => this.price() * this.quantity());
}

effect()

effect() एक साइड इफ़ेक्ट (लॉगिंग, localStorage, एनालिटिक्स) अपने-आप चलाता है जब भी वे सिग्नल बदलते हैं जिन्हें यह पढ़ता है।

import { effect } from '@angular/core';

constructor() {
  effect(() => {
    console.log('Total is now', this.total());
  });
}

computed बनाम effect

जब आपको वापस कोई मान चाहिए तो computed() उपयोग करें; जब आपको बस प्रतिक्रिया में कुछ करना है (कोई मान वापस नहीं) तो effect() उपयोग करें।