1

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()
  }
}
pennylies
  • 25
  • 4
  • Browser garbage collects resources on page close. Given you've added logic to check user is defined (and so bad logic isn't running as page closes) and added ngOnDestroy for when service *could* be destroyed if provided to a smaller scope in application...I think this is fine – Andrew Allen Dec 13 '22 at 15:09

3 Answers3

2

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

nate-kumar
  • 1,675
  • 2
  • 8
  • 15
2

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.

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
0

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

dt170
  • 417
  • 2
  • 12