Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an angular service provided to a component destroyed when the component is destroyed?

Tags:

angular

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?

like image 894
nephiw Avatar asked Oct 21 '25 03:10

nephiw


1 Answers

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.

like image 123
Ploppy Avatar answered Oct 23 '25 18:10

Ploppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!