Usage of Destroy Method in Angular Service

Posted By : Avilash Choudhary | 26-Sep-2018

Hi Guys, Today we are going to discuss Angular components life cycle ngOnDestroy method.

As we know components have a ngOnDestroy method in their life cycle, but the question is do Angular Service have ngOnDestroy method ??

 

The answer is YES.

 

Angular services also have destroyed method which is called when service is destroyed and we can do our cleanup things, such as unsubscribe from subscriptions, clean service level variables.

Now there is the twist, the ngOnDestroy method will not work every time, if you have provided your service in components providers the ngOnDestroy method will be called but if you have provided it in module level providers then it won't be called because your service is not destroyed yet.

 

Below is the example, how to provide services in the module

import { NgModule } from '@angular/core';
import { HomeComponent } from './home.component';
import { HomeService } from './home.service';

@NgModule({
  imports: [],
  declarations: [HomeComponent],
  providers: [HomeService],  // This service will be singleton it will have same instance for all components who will use it
  exports: [HomeComponent]
})
export class HomeModule { }

Below example show services provide in component

@Component({
  moduleId: module.id,
  selector: 'sd-home',
  templateUrl: 'home.component.html',
  providers: [HomeService],  // This service will be singleton only for this component
  styleUrls: ['home.component.css'],
})
export class HomeComponent {

}

If you have some complex application with lots of objects and you store data in your service, its better you keep data in single service which will be provided in module level and will be used by all the components but if you don't store data in services its better to provide it in components and it will get destroyed when component is destroyed.

 

Try to clean all data of module-level services manually when your module is destroyed, because it may create memory leaks which are not easy to find out.

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..