ng-disposable

A library for setting up and disposing services

Usage no npm install needed!

<script type="module">
  import ngDisposable from 'https://cdn.skypack.dev/ng-disposable';
</script>

README

ng-disposable

Description

ng-disposable is a small library that lets you implement a disposable interface and add it to a list of services in order to tear down multiple services at once on a given condition.

Useful if you manage subscriptions or other state inside services that should be cleaned up simultanously e.g. on logout

Simply implement the Disposable interface and add the service to the DISPOSABLES injection token list using multi: true Then invoke the dispose function on the provided DisposableService

Usage

Implement the Disposable interface:

export class MyService implements Disposable {
  public dispose() {
    // tear down
  }
}

Add your disposable service to the module:

@NgModule({
  imports: [DisposableModule.forRoot()],
  providers: [
    MyService,
    {
      provide: DISPOABLES,
      useExisting: MyService,
      multi: true
    }
  ]
})
export class MyModule {}

use the DisposableService to tear down all disposables:

export class AppComponent {
  constructor(private service: DisposableService) {}

  public logout() {
    this.service.dispose();
  }
}

Contribute