Home > Software design >  Angular Does ngOnDestroy run inside the service?
Angular Does ngOnDestroy run inside the service?

Time:12-14

I have a service this service should run until the project is started and closed. After the application(website) is closed, the ngondestroy method of the service should run. How do I know if the ngondestroy method in the service is working? does this ngondestroy work?

export class UserServiceService implements OnDestroy{
subsc : Subscription
constructor(private auth : AngularFireAuth,private db : AngularFireDatabase,private fnc:AngularFireFunctions,private router : Router,private tostr : ToastrService) {

 this.subsc =    this.auth.authState.subscribe((user) => {
      if (user) {
         this.db.database.ref("users/" user.uid "/shopCart/").on("value",snap=>{
         })
      } else {
        //not user
      }
    });
  }

  ngOnDestroy(): void {
    console.log("Closed")
    this.subsc.unsubscribe()
    this.db.database.ref("users/" this.currentUserId "/shopCart/").off()
  }
}

CodePudding user response:

As @nate-kumar said angular does not fire the ngOnDestroy life cycle hook when the user closes the browser.

The best workaround for achieve this is to use something below :

export class AppComponent {
  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    // do the needful here
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHandler(event) {
    // do the need full here
  }
}

Please find the working stakblitz here.

CodePudding user response:

ngOnDestroy unfortunately does not fire when a browser window is closed. It is only triggered when a component/service/directive is destroyed while the Angular application is alive.

If you need to trigger logic when the browser window is closed, some solutions have involved using the onbeforeunload hook on the window object:

See ngOnDestroy not firing on page reload

CodePudding user response:

Angular service does not using ngOnDestroy by default but...

When implementing ngOnDestroy in service you can link it to a component ngOnDestroy.

Meaning when the component will get destroy the ngOnDestroy the ngOnDestroy of the service will get call also.

This is very useful if you want to unsubscribe or remove data when there is not need for it any more.

In order to link service ngOnDestroy to component ngOnDestroy add it to the component providers and implement ngOnDestroy in the service.

@Component({
  selector: 'app-test',
  templateUrl: './app-test.component.html',
  styleUrls: ['./app-test.component.scss'],
  providers: [YourService],

})

But for the case you mentioned check this ngOnDestroy not firing on page reload

  • Related