1.0.6 • Published 11 months ago
ngx-unsub v1.0.6
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
- Import the decorator in the component
import { NgxUnsubscribe } from 'ngx-unsubscribe';
- 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
- No need of manual unsubscription
- No need of adding ngOnDestroy method
- No need of adding decorator to each method
- No need of declaring Subscription or Subscription array variables
- Light weight package