how to access lazy loaded service methods from caller method?

In my module I am lazy loading(lazy.module.ts) a module from app.component.ts by using a testService. After successfully loaded the function I need to access a function from where I loaded the module. How can I achieve?

app.component.ts

import { Component } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private _testService: TestService) {}

  //lazy start
  public loadme = function(){

    console.log('begin load')
    this._testService.load();    
  }
}

app.component.html

<button (click)="loadme()">Load me</button>

test.service.ts

import { Injectable, NgModuleFactoryLoader, Injector, NgModuleRef } from '@angular/core';

@Injectable({ providedIn: 'root', })
export class TestService {

  constructor(
    private loader: NgModuleFactoryLoader,
    private injector: Injector
  ) { }

  private moduleRef: NgModuleRef<any>;

  load(): void {

        const path = 'src/app/lazy.module#LazyModule'
        this
            .loader
            .load(path)
            .then(moduleFactory => {
                this.moduleRef = moduleFactory.create(this.injector).instance;                
               console.log('loaded');  

               //I NEED TO ACCESS THE 
               //lazyService.hello()   function here
            })
            .catch(err => {
                console.error('error loading module', err); 
            });

  }
}

lazy.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LazyService } from './lazy.service';

@NgModule({
  declarations: [],
  imports: [ CommonModule ],
  providers:[ LazyService ]
})
export class LazyModule { }

lazy.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class LazyService {

  constructor() {    
    console.log('lazy service constructed');    
  }

  //I NEED TO ACCESS THIS FUNCTION RIGHT AFTER LAZY LOADS
  public hello = function():void{

    console.log('Hello from lazy service');
  }
}

1 answer

  • answered 2018-11-08 08:49 Antoniossss

    provide service tokens in lazy.module.ts

      ,
      providers:[
        {provide: 'LazyService', useClass: LazyService}
      ]
    

    test.service.ts

    Since you have module reference, you can use its injector to create required service

    .then(moduleFactory => {
       this.lazyModule = moduleFactory.create(this.injector);
    
        var lazyService = this.lazyModule.injector.get('LazyService');
        lazyService.hello()
    
    })