angulartypescriptobservable

How can I unsubscribe from an 'any' 'var' observable in Angular when the component is destroyed?


Consider:

@Input()
var:any;

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

I tried var.unsubscribe(), and it 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 asynchronous 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 stuff
    
                })
            ).subscribe()
        }
    
        ngOnDestroy() {
            this.onDestroy.next();
            this.onDestroy.complete();
        }
    }