Sunday 7 November 2021

Angular service Re-initialised / Angular service instantiated many times

 Hey Guys,

Recently i came cross a problem with Angular 2 + service  constructor got called multiple times. 


Generally , Angular services are singleton meaning it will be called / instantiated only once across the app if the scope of injection is root. 


If we want to re-create / call constructor mutliple times then we have to keep the service in the specific module PROVIDERS. When we specify in providers then the service will be re-created for that particular module you specified. 

The issue i faced:

 > we have the service with  root injectable.  it clearly states that the service available across the root. 

@Injectable({
  providedIn: 'root'
})
export class TestService
But we kept the service in Providers for particular module say  TestModule
providers: [
    TestService
  ]
This causing the service to be called many times and all the data inside service is re-freshed. 

so, when u keep the service at injectable root then dont put it in providers until its needed or necessary. 


No comments:

Post a Comment