Search code examples
angularangular-directive

With Angular Directives, do Service subscriptions need to be unsubscribed?


Using Angular 10, I have a Directive that listens to a Service. Do I need to unsubscribe from that Observable in this scenario?

For example:

@Directive({
    selector: '[appShowFoo]'
})
export class ShowFooDirective {
    @HostBinding('class.foo') foo: boolean;

    constructor(private _fooService: FooService) {
        this._fooService.foo$.subscribe(foo => this.foo = foo);
    }
}

Solution

  • Always unsubscribe. Active subscriptions are what occupy memory and if not cleaned cause a memory leak, not where you use them.

    Something like this will clean the subscription upon observable completion.

    const sub = this.observable$.subscribe(
        value =>{...}, 
        error => {...}, 
        /*onComplete*/
        () => sub.unsubscribe()
    );
    
    

    For one shot operations you may just call toPromise() and use then or await.