I'm using Angular 2+.
As part of a ngOnDestroy for a component, I'd like to destroy/delete a service instantiation.
Is this possible?
Anyone know how?
And also of course, the next time the component is loaded, I'd like to recreate the service and then destroy when the component dies.
Edit:
What I'm trying to achieve is a dedicated web socket per component. And when a component gets destroyed (ngOnDestroy), to disconnect the websocket.
I'm assuming that you have your module's providers array contain the service. Remove it from there and just scope it to the component like so:
@Component({
selector: 'yb-page',
providers: [ServicePerComponent]
})
This basically will prevent angular from making a singleton for the service. It will instead create a new service per component. So once this component dies you can run the cleanup logic for the service in the onDestroy.
More info here: https://angular.io/guide/hierarchical-dependency-injection