How to make components in Angular 2 singleton?

I am using Angular 2 to build my web application that has many components. I use angular-cli to create, run and create a project.
By chance (or, fortunately), I came across an error, where I realized that several instances of my component are being created. Even worse, I realized that my code refers to any of these instances randomly, without any logic to track it.

As an example, check the following scenario:

  • I went into my application and made a REST call (window resize event) in a specific component
  • The important point here is that each user has a unique identifier that is used in REST calls
  • Then I logged out of this user and logged in with another user.
  • I returned to the same component and made the same rest calls (again with window resizing events), however, to my shock, some of the remaining calls were made using a unique identifier or a previously registered user
  • To test my suspicion, I created a first class variable in the constructor, which basically stores the value Date.now(). This twist will tell me when the class was created.
  • Then I added a few statements console.log()that show which instance is invoked by the value of my variable.
  • The magazine confirmed my suspicion that several instances really exist simultaneously, and there is no specific logic or path to access any of them. This is an image of my log statement.  I denigrated the sensitive parts.

. . , 1, - . . - , .

:

  • singleton?
  • ?
+4
1
  • singleton?

,

  1. ?

, OnDestroy

export class ClockComponent implements OnDestroy {
interval;

ngOnDestroy() {
  clearInterval(this.interval);
}

constructor() {
  this.interval = setInterval( ()=> console.log('tick') );
}
0

Source: https://habr.com/ru/post/1668371/


All Articles