I am using Angular 2 to build my web application which which has lot of components. I am using angular-cli to create, run and build the project.
Accidentally (or luckily) I stumbled across a bug where I realized that multiple instances of my component were being created. Even worse was when I realized that my code was referring to any one this instances randomly without any logic to trace it back.
Date.now()
. This is turn would tell me when the class was instantiated. console.log()
statements which would show me which instance was being called by the value of my variable. This is the image of my log statement. I have blackened out the sensitive parts. It can be clearly seen that some rest calls are being made with the unique id for tenant 1 while some for trial tenant. Also use of two instances is also very clear from two instance times. The old instance of previous logged in tenant is somehow still in play and my component is still able to access it.
- Is there a way to make the component class singleton?
not that i am aware of
- Is there any way to destroy the component instance on leaving the component?
yes, there is an interface OnDestroy
export class ClockComponent implements OnDestroy {
interval;
ngOnDestroy() {
clearInterval(this.interval);
}
constructor() {
this.interval = setInterval( ()=> console.log('tick') );
}