'ngDestroy executed too late: unable to call specif dispose method

I guys, I'm having a problem using ngDestroy. I need to call a "stop" method on a object initialized during ngInit, but when ngDestroy is called this object is already null. If I don't call that stop method, a background process won't be stopped and after some time I start to receive errors.

How can I do it?


This is how I'm writing my component

@Component({ templateUrl: 'sample.component.html' })
export class SampleComponent implements OnInit, OnDestroy {

  constructor() {  }

  myObject : MyObject = null;

  ngOnInit() {
    this.myObject = new MyObject();
    this.myObject.Start();
  }

  ngOnDestroy() {
    this.myObject.Stop();   //<== when ngOnDestroy is executed myObject is "undefined"
    this.myObject = null;
  }
}

When ngOnDestroy is called, myObject is already undefinied so I cannot call Stop method. If that method is not called, the background process started during ngOnInit will work forever.

How can I solve it?



Solution 1:[1]

Try this:

ngOnDestroy() {
   if (!!object) { // check if the object is not null with the double bang (!!)
     object.stop(); // if it is truthy, then go ahead and call the stop method.
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AliF50