I have a service with an interval that checks the state of the data every 10 seconds to update a label in a component. This is only required when on the page where the component exists. The component looks a little like this:
@Component({
selector: 'editor-status',
templateUrl: './editorStatus.component.html',
providers: [EditorStatusService]
})
export class EditorStatusComponent implements OnDestroy {
constructor(private service: EditorStatusService){};
public ngOnDestroy(): void {
service.destroy();
}
}
My service has this kind of structure:
@Injector()
export class EditorStatusService {
private intervalId: any;
constructor() {
this.intervalId = setInterval(() => {
/* code to update ui */
}, 10000);
}
public destroy(): void {
clearInterval(this.intervalId);
}
}
Are services provided to components in this way built each and every time the component is instantiated? If I don't destroy the listeners will I create a memory leak each time this page is loaded and then navigated away from?
A service provided by a component is automatically destroyed when the component is destroyed.
You can test this via the ngOnDestroy life cycle hook in your service:
ngOnDestroy(): void {
console.log('service destroyed');
}
It should write 'destroyed' in console when the component is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With