I\'ve been following this tutorial, to understand lazy loading, and below is my inference.
Scenario 1: Services are provided by putting them in the
Here is the way I do it: https://stackblitz.com/edit/angular-lazy-service-module?file=src%2Fapp%2Fapp.component.ts
This is a proof of concept. You need to watch out what injector you use (in case the lazy service need some dependencies) and how you manage the life-cycle of the lazy loaded service (how many instances you create, etc.).
My use case is that there is a pretty big service (export to excel, over 400 KB gziped) that is used in multiple areas of the application but I don't want to load/parse it until it's actually needed - faster initial load! (I actually also used a delay preload strategy that loads the modules after a few seconds).
The basic idea is that you define it as a lazy module in a route (that you don't actually use) but you trigger the load manually. You also resolve the service from that module (once you have it) by using an injection token.
lazy module
import { NgModule } from '@angular/core';
import { LazyService } from './lazy-service.service';
import { LAZY_SERVICE_TOKEN } from './lazy-service.contract';
@NgModule({
providers: [{ provide: LAZY_SERVICE_TOKEN, useClass: LazyService }],
})
export class LazyServiceModule {
}
lazy service
import { Injectable } from '@angular/core';
import { LazyService as LazyServiceInterface } from './lazy-service.contract';
@Injectable()
export class LazyService implements LazyServiceInterface {
process(msg: string) {
return `This message is from the lazy service: ${msg}`;
}
}
app module
@NgModule({
imports: [BrowserModule,
RouterModule.forRoot([
// whatever other routes you have
{
path: '?$lazy-service', //some name that will not be used
loadChildren: 'app/lazy-service/lazy-service.module#LazyServiceModule',
},
])],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
using it inside a component
constructor(
private loader: NgModuleFactoryLoader,
private injector: Injector,
) {
}
async loadServiceAndCall() {
const factory = await this.loader.load('app/lazy-service/lazy-service.module#LazyServiceModule');
const moduleRef = factory.create(this.injector);
const service: LazyService = moduleRef.injector.get(LAZY_SERVICE_TOKEN);
this.value = service.process('"from app.component.ts"')
}
providedIn: 'root'
is the easiest and most efficient way to provide services since Angular 6:
For further informations consider reading the documentation and NgModule FAQs
Btw:
*UPDATE
'use the provider's array of NgModule instead' means to use the providers array of the lazy loaded module, eg:
import { NgModule } from '@angular/core';
import { UserService } from './user.service';
@NgModule({
providers: [UserService],
})
export class UserModule {
}
OR to actually name the module in the injectable decorator:
import { Injectable } from '@angular/core';
import { UserModule } from './user.module';
@Injectable({
providedIn: UserModule,
})
export class UserService {
}
Quote from the docs:
When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector.
Doc ref: https://angular.io/guide/providers#providedin-and-ngmodules
This thread is pretty old but I'll answer what I learned while searching on this topic for the future stumblers on this thread.
The concept of privatizing a service with lazy loading is proper and for the below reasons:
Angular Doc says that one of the ways to scope your service is to provide them to its own module(suppose Module-A). And only when any other module B imports module A, then it will have the provider of that service(from module A) and thus can access it. This actually works for lazy modules and not for eager modules for below reasons:
When you do implement the above scoping method for eager modules, it will create a provider for the services of that module(suppose module A). But when that particular module 'A' is imported into the root module(as all eager modules should be), the root injector will create a single instance of that service and would discard any duplicate instance of that service in the root injector's scope(if module A was imported in any other eager module). Thus all eager modules have access to a singleton service of any module which was imported in the root module.
If you still want to have access to the lazy service from the root injector. You can use the:
@Injectable({
providedIn: 'root'
})
decorator in the lazy service and inject it in the root injector without loading the lazy module at application load.
The example you were following is not a true implementation of lazy loading if you have access to the lazy services in your root module, without the providedIn: root
object. You can go through this link: https://angular.io/guide/providers#limiting-provider-scope-by-lazy-loading-modules
The best explanation I could give you is in this article.
Anyway, in short:
For Lazy loading services you can check below link
[How do I provide a service in a lazy-loaded module and have that service scoped to just the lazy-loaded module and its components?