Service instantiated twice after APP_INITIALIZER

angular initialize service on startup
app_initializer not working
angular app_initializer config
angular service
angular test app_initializer
angular service constructor called multiple times
angular singleton service
app_initializer router

Problem is: I need to make an http call and store an object that is needed for generate dynamic routes. So, I was taking advantage of the APP_INITIALIZER.

// app.module.ts
import { ApplicationService } from './application.service';


providers: [
  ApplicationService,
  { 
  provide: APP_INITIALIZER, useFactory: appServiceFactory, deps: 
  [Injector, ApplicationService], multi: true 
  },
],

function appServiceFactory(injector: Injector, appService: ApplicationService): Function {
  return () => {
    return appService.loadApplication().then((app: Application) => {
      /custom logic
      });
    });
  };
}


// application.service.ts
@Injectable({
  providedIn: 'root'
})

// navigation.component.ts
import { ApplicationService } from './application.service';

export class NavigationComponent implements OnInit {

    constructor(private _applicationService: ApplicationService) {
  }

}

But inside navigation.component, applicationservice is initialized again. I'm sure of that because if I log or put a debugger statement, the construct() method of the service is called twice.

Why even if the Service is declared as singleton with the providedIn: root is being reinstantiated?

The reason for this is that once you include Router in dependencies to your APP_INITIALIZER factory you get circular dependency (https://github.com/angular/angular/blob/4c2ce4e8ba4c5ac5ce8754d67bc6603eaad4564a/packages/router/src/router_module.ts#L61-L64).

ApplicationService
       |
    TestService
       |
     Router
       |
  ApplicationRef
       |
ApplicationInitStatus
       |
 APP_INITIALIZER
       |
ApplicationService

To solve this you can get Router lazily:

export class TestService {

  get router() {
    return this.injector.get(Router)
  }

  constructor(private _http: HttpClient, private injector: Injector ) {
  }
}

Forked Stackblitz

Service instantiated twice after APP_INITIALIZER - angular - html, Service instantiated twice after APP_INITIALIZER - angular. application.service'​; export class NavigationComponent implements OnInit { constructor(private  APP_INITIALIZER is imported from @angular/core There can be multiple APP_INITIALIZER injection tokens…they are run concurrently and the initialization process is complete when they all finish Use the “multi: true” option for multiple injection tokens, to restrict to one, use “multi: false”

Based on your Explanation that you have added the providedIn: root in the application.service.ts , that means it will be added to the root module (i.e Appmodule.ts) and again in the Appmodule.ts in your provider array you are adding ApplicationService.

From this Blog its state that

"There is now a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module."

this is creating the service to be reinstantiated

Edit1 : Another thing to check is , 1. How are you calling this service i mean in Dev mode or Prod mode , if its dev mode then service will be called twice

If you're running in development mode, it will run the function at least twice. since in development mode it does a check, changes, then rechecks to verify, where production mode only does the first check, assuming you've done your quality assurance and resolved any values the get changed post checking.

Source

Try to check in Prod Mode and verify it..

Service instantiated twice after APP_INITIALIZER, Service instantiated twice after APP_INITIALIZER. Multi tool use. 0 provide: APP_INITIALIZER, useFactory: appServiceFactory, deps: [Injector  #A clear and concise description of what the bug is. When registering a service using AddScoped(Type, Func<IServiceProvider, object>) the instance is created twice. To Reproduce 1: Cr

Found the problem: it was because of the Router, needed as dependency by a service injected in ApplicationService.

See example: https://stackblitz.com/edit/angular-xwyugy

When Router is removed from the ApplicationService, the double instantiation is gone.

Can't understand why, so I'll wait for a better answer for approving.

Router 3.2.0, After upgrading to router 3.2.0, services being provided by component module are being instantiated twice. Once while resolver is being run  After upgrading to router 3.2.0, services being provided by component module are being instantiated twice. Once while resolver is being run (last place in router is PreActivation.prototype.getToken) and then again later during activation (last place in router is RouterOutlet.prototype.activate).

I also faced an issue that my service was instantiated twice and from what I've seen in logs, one constructor was called from config.service.ts file and second from config.service.js (note the extension difference). It occurred that by mistake I imported my service like this:

import { ConfigService } from '../config/config.service.js';

instead of:

import { ConfigService } from '../config/config.service';

Changing it to proper import solved the issue.

Factory providers are called before APP_INITIALIZER is resolved , Factory provider functions executed after APP_INITIALIZER resolved. return b()​; need to use env config values in services created by factory. Configuring APP_INITIALIZER. We are going to provide APP_INITIALIZER inside App Module, but this can be done in any other module like CoreModule. Before we can do that, we need to create a function to the method for getting our configuration. The function will accept our config service above, which we shall inject when providing APP_INITIALIZER.

Hook into Angular's Initialization Process, APP_INITIALIZER is one of the injection tokens of Angular. quite so much latency and you can also use the existing services and framework features. So there are two functions called in the initialization process — . When you choose to fit in this process, do it after consideration because it suspends  But if the same service is injected in an HTTP_INTERCEPTOR and we try to access the property , then it says the property is undefined which implies that the constructor for the interceptor is trying to access the property before the APP_INITIALIZER is resolved.

Loading App Configuration in the APP_INITIALIZER, It's minor change after minor change, followed by deploys, that don't seem application needed is a service, which I called AppConfigService . yep, the effects no doubt use some of your regular services, which in turn triggers them to be initialized. Also note that variable declarations at the start of your classes will run too, so best to declare your variables empty, and then use a function called from your constructor (or elsewhere) to actually fill them with your data after APP_INITIALIZER completes. also be careful with get

Hooking into the Angular bootstrap process, From this article you'll learn how to use APP_INITIALIZER token and This is the function that Angular calls when instantiating the application. After running into such functionality in the sources I checked the documentation  For example, you might enable logging as a method-call on a service after it has been instantiated by Angular. Such a method invocation could be done in a run block. But, more than anything, I just want to demonstrate what is possible so that you can be educated in how you approach configuration in an Angular 2 application.

Comments
  • Can you show use how you're importing module?
  • @PankajParkar added
  • I mean to say how you are importing module inside NgModule's imports array. this module is loaded lazily or eagerly?
  • @PankajParkar the service is loaded inside the root module. I'm using only 1 module.
  • what is appServiceFactory, I don't see that function anywhere in the code.
  • If I remove the providedIn: root declaration, it still keeps being instantiated twice. Also, I can't remove it from the providers array because it's needed for the appServiceFactory function provided to APP_INITIALIZER
  • @lucgenti it would be better if you can keep the code in slackblitz or any other means so that it will help in debugging more. right now we will be giving the solutions on case by case which is of no use
  • stackblitz.com/edit/angular-xwyugy but here seems like is getting instantiated just one time
  • instead, in my app it keeps doing that even if enableProdMode();
  • seems like the problem is not that the service is instantiated twice beacuse of dependency injection in a component. It's during the bootstrap that it's been called twice (1 for the module, 1 for the factory). So the data retrieved from the factory is lost.
  • Had a similar issue, except mine was because I added the parent module to my module so that I could use a component (loaded in the parent module) in my module. It felt wrong at the time, but was strangely the only way I could add that particular component (tried all the exports and entryComponents stuff). Anyway, ended up extracting the component to a "common" module, which I included my module and the resolved the issue like yours.