Search code examples
angularsubscribeunsubscribetake

How to unsubscribe using take operator?


How can I unsubscribe from this using take operator?

constructor(/*params*/) {
  let id = this.route.snapshot.paramMap.get('id');
  if (id) this.productService.get(id).valueChanges().subscribe(p => this.product = p);
}

Solution

  • If you mean the take(1) operator to only fetch the value once, and complete the Observable right after, and with it unsubscribe all the subscriptions, you can do the following :

    this.productService.get(id).valueChanges().pipe(
      take(1)
    ).subscribe(p => this.product = p)