1.0.6 • Published 11 months ago

ngx-unsub v1.0.6

Weekly downloads
-
License
-
Repository
github
Last release
11 months ago

ngx-unsub

Simple package to automatically handle all the subscription at the class level

Supports Angular v12 to v17

Installation

npm i ngx-unsub

Usage

  1. Import the decorator in the component
import { NgxUnsubscribe } from 'ngx-unsubscribe';
  1. Add the decorator to the top of the class
@NgxUnsubscribe()
export class HomeComponent implements OnInit {

}

Thats it !!!

You heard it right.

Yes the package will take care of every method which has return type Subscrption

For example:

@NgxUnsubscribe()
export class HomeComponent implements OnInit {
  constructor(private apiService: ApiService) {}

  count = 0;
  count2 = 0;

  ngOnInit() {
    this.getCount();
    this.getCountTwice();
    this.getPosts();
    this.getComments();
  }

  getCount(): Subscription {
    return interval(2000).subscribe(() => {
      this.count += 1;
      console.log(this.count);
    });
  }

  getCountTwice(): Subscription {
    return interval(500).subscribe(() => {
      this.count2 += 2;
      console.log(this.count2);
    });
  }

  getPosts(): Subscription {
    return this.apiService.getPosts().subscribe((res) => {
      console.log(res);
    });
  }

  getComments(): Subscription {
    return this.apiService.getComments().subscribe((res) => {
      console.log(res);
    });
  }
}

Here actually see can the methods getCount(), getCountTwice(), getPosts() and getComments() have return type Subscription. But none of those subscriptions are unsubscribed in ngOnDestroy().

Here the decorator comes in help which automatically decide the subscription based on return type and unsubscribes it.

Note: function should have return keyword and return type should be Subscription

Advantages of using this package

  1. No need of manual unsubscription
  2. No need of adding ngOnDestroy method
  3. No need of adding decorator to each method
  4. No need of declaring Subscription or Subscription array variables
  5. Light weight package
1.0.6

11 months ago

1.0.4

11 months ago

1.0.3

11 months ago

1.0.2

11 months ago

1.0.1

11 months ago