gog
gog

Reputation: 12968

How to destroy a service instance in angular?

In my Angular app I need to share a service instance between one component to another component, and after that destroy the service instance, how to do that?

       AppModule
     /          \
 Module1        Module2
   /               \
ProductComponent    LogComponent              ? LogService

The ProductComponent:

   constructor(private _logService: LogService) { }

   viewLog() {
      this._logService.productId = this.product.id;
      this._router.navigate(['/app/administration/logs']);
   }

The LogComponent :

  constructor(private _logService: LogService, private _adminService: AdminService) {

       this._adminService.getLogs(_logService.productId).subscribe(.....);
  }

I put the LogService on AppModule to create a Singleton. It works ok, but i dont want to keep this LogService instance after the user leaves the LogComponent. I need to destroy it. How can I do that?

Upvotes: 2

Views: 10480

Answers (2)

Balita
Balita

Reputation: 59

@Component({
   selector : 'your-selector',
   template : 'your template',
   providers: [LogService]
})
export class LogComponent {
  // your implementation here
}

Upvotes: -1

Jun Kang
Jun Kang

Reputation: 1275

As far as I'm aware, you can't do what you are asking. My suggestion would be to include a function in LogService that will clear out the data you want to get rid of once it's been used. For example:

export class CurrentUserService {
  productId: number | null;

  clearProductId() {
    this.productId = null;
  }
}

And simply call it when you want to "destroy your service" because you can't actually destroy the service when you're providing it in this way. If you were to somehow actually destroy the service at the AppModule level, any component which uses that service would fail, including your LogComponent, because it depends on that injection.

Upvotes: 3

Related Questions