Search code examples
angulartypescriptobservable

How can I unsubscribe from a any var observable in angular when component is destroyed?


@Input() var:any;

var passed as an observable but I'm getting a var.unsubscribe() is not a function when ngDestroyed is called.

I tried var.unsubscribe() and is not working


Solution

  • Use the async pipe inside the template and avoid (as much as possible) subscribing inside the component. if you must subscribe inside the component (.ts file) use the following approach for unsubscribing. don't do that inside services!

    export class MyComponent {
    
       private readonly onDestroy = new Subject<void>();
    
       products$: Observable<Product>;
    
       constructor(private myService: MyService) { }
       
       ngOnInit(): void {
        
        // the right way
        // don't forget to use the async pipe inside the template
        this.products$ = this.myService.getMyProducts(); 
    
    
        // not the best way
        this.myService.getMyProducts().pipe(
          takeUntil(this.onDestroy),
          tap((products: Product) => {
             
             // do your staff
             
          })
        ).subscribe()
    
       }
       
       ngOnDestroy() {
         this.onDestroy.next();
         this.onDestroy.complete();
       }
    
    }