Monday, 12 November 2018

Service destroyed after instantiation during APP_INITIALIZER

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 },
],

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

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

export class NavigationComponent implements OnInit {

    state = 'closed';
    isLoggedIn$: boolean;
    languages: string[];
    currentUrl: string;

    constructor(private _applicationService: ApplicationService) {
  }

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

But inside navigation.component, applicationservice is initialized again.

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



from Service destroyed after instantiation during APP_INITIALIZER

No comments:

Post a Comment