Skip to content

Instantly share code, notes, and snippets.

@vespertilian
Created October 8, 2020 04:26
Show Gist options
  • Save vespertilian/7ad0a4817079817dc8c85663cf686417 to your computer and use it in GitHub Desktop.
Save vespertilian/7ad0a4817079817dc8c85663cf686417 to your computer and use it in GitHub Desktop.
Use an on destroy service provider instead of creating a subject and destroying it for every component
// Service
@Injectable()
export class OnDestroyService implements OnDestroy {
triggered$ = new Subject()
ngOnDestroy() {
this.triggered$.next()
this.triggered$.complete()
}
}
// Use in providers
@Component({
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss'],
providers: [
OnDestroyService
]
})
export class MyComponent implements OnInit {
constructor(private onDestroy: OnDestroyService, private fooService: FooService) { }
ngOnInit() {
fooService
.getData
.pipe(takeUntil(this.onDestroy.triggered$))
.subscribe((v) => console.log(v))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment