0

I have a doubt about when is destroyed a provider on Angular.

This is my a part of my provider:

 ...
    @Injectable()
    export class ApiHelper {
    private myState = {};
    constructor(){
       console.log('constructor');
     }
    ...
    }

It is injected on Page Module (Lazy Loading) as a provider. When I enter for the first time to the page the log is showed and the myState variable is {}.

If I modify the myState variable with info and exit of this page and enter again, the page is detroyed and created again but the log of Providers constructor is not showed and the myState content is the last value modified into the page.

When I create a new instance of a page (constructor is executed) the injected provider is not created again?

Thanks

Hanzo
  • 1,839
  • 4
  • 30
  • 51
  • A service lives as long as the module it is provided in lives. Unless you add it to the component selector, then it lives as long as that component. So from the description, it sounds like the service is provided in the parent of the lazyloaded module. – Inge Olaisen Jan 31 '20 at 10:56
  • The service is In Providers section of the page module file. And in the @Injectable decorators is not identified as a root. The page , I think, is destroyed and created again correctly because i have log into the constructor and it shows every time i enter on it. However the log on provider constructors only shows the first time I enter on page – Hanzo Jan 31 '20 at 15:48
  • Easy way to check is have the service log a message in your ngOnDestroy. Then you can see if it is created multiple times and destroyed multiple times or just created and never destroyed. – Inge Olaisen Feb 01 '20 at 10:53

0 Answers0