0

May you explain me some fact? I have this code

sharedservice.ts


@Injectable({
  providedIn: 'root'
})
export class SharedService {
  id = (new Date()).getTime();
}

main.ts

export const ROUTES: Route[] = [
  {
      path: 'lazycomp',
      loadComponent: () =>
          import('./lazycomp.component').then(
              (mod) => mod.LazycompComponent
          ),
  },
];

@Component({
  selector: 'app-root',
  standalone: true,
  template: `

    {{serv.id}}

    @if(!(loaded$ | async)) {
      <button (click)="load()">
          Load advanced settings
      </button>
    }
    <ng-container *ngComponentOutlet="comp" />
  `,
  imports:[CommonModule],
  providers: []
})
export class App {
  loaded$ = new BehaviorSubject<boolean>(false);
  comp: any;

  readonly serv = inject(SharedService);

  async load() {
    this.comp = await import('./lazycomp.component').then((mod) => mod.LazycompComponent);
    console.log(this.comp);
    this.loaded$.next(true);
  }
}

bootstrapApplication(App);

lazycomp.component

@Component({
  selector: 'app-lazycomp',
  standalone: true,
  imports: [LazycompimpComponent],
  template: `
    lazy  =  {{serv.id}}
  `,
  styles: ``,
  providers: []
})
export class LazycompComponent {
  readonly serv = inject(SharedService);
}

lazycompimp.component

@Component({
  selector: 'app-lazycompimp',
  standalone: true,
  imports: [],
  template: ``,
  styles: ``,
  providers: [SharedService]
})
export class LazycompimpComponent {

}

I press button, load lazycomp and get 1717188440363 lazy = 1717188440363.

Ok. service instance is singleton and on root injector.

After that I add providers: [SharedService] to lazycomp and get 1717189116834 lazy = 1717189194305

How it work? Why imports: [LazycompimpComponent] in lazycomp does not put SharedService to providers?

I thought that lazy loaded module (standalone component module too?) create own root injector.

1
  • Lazy loaded modules don't create their own root injector. There is one root injector, and lazily loaded modules create their own injector that is a child of the application root injector. Commented May 31, 2024 at 21:47

1 Answer 1

0

Every eagerly loading module, will setup providers in the Root Injector. This includes nested imports in nested modules.

Lazy loaded module will create their own injector (as you can't add providers to an exisiting injector).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.