В моем модуле я лениво загружаю (lazy.module.ts
) модуль из app.component.ts
с помощью testService. После успешной загрузки функции мне нужно получить доступ к функции, откуда я загрузил модуль. Как я могу достичь?
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');
}
}