如何从调用方方法访问延迟加载的服务方法?

how to access lazy loaded service methods from caller method?

在我的模块中,我使用 testService 延迟加载(lazy.module.ts)来自 app.component.ts 的模块。成功加载函数后,我需要从加载模块的位置访问函数。我怎样才能实现?

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');
  }
}

lazy.module.ts

中提供服务令牌
  ,
  providers:[
    {provide: 'LazyService', useClass: LazyService}
  ]

test.service.ts

因为你有模块引用,你可以使用它的注入器来创建所需的服务

.then(moduleFactory => {
   this.lazyModule = moduleFactory.create(this.injector);

    var lazyService = this.lazyModule.injector.get('LazyService');
    lazyService.hello()

})