I am trying to understand why my lazy loaded module, which loads the test component, does not allow the test component to subscribe to an observable injected by a test service.
index.ts
export { TestComponent } from './test.component';
export { TestModule } from './test.module';
test.component.ts
import { Component, OnInit } from '@angular/core';
import { TestService } from './test.service';
import { Observable } from 'rxjs';
@Component({
selector: 'test',
template: `
<p>{{test | async}}</p>
`,
})
export class TestComponent {
test: Observable<number>;
constructor(private testService: TestService) {
this.test = this.testService.getObservable();
}
}
test.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';
import { TestService } from './test.service';
@NgModule({
declarations: [TestComponent],
imports: [
CommonModule,
],
providers: [TestService]
})
export class TestModule { }
test.service.ts
import { Injectable } from '@angular/core';
import { from, Observable } from 'rxjs';
import { delay } from "rxjs/operators";
@Injectable()
export class TestService {
getObservable(): Observable<number> {
return from([...Array(10).keys()].reverse())
.pipe(
delay(1000)
)
}
}
app.component.ts
import { Component, ViewChild, ViewContainerRef, Compiler, Injector, Type, NgModuleFactory } from '@angular/core';
import { TestModule } from './test';
@Component({
selector: 'app-root',
template: `
<ng-container #vc></ng-container>
`,
styles: []
})
export class AppComponent {
@ViewChild('vc', { read: ViewContainerRef }) containerRef: ViewContainerRef;
constructor(private compiler: Compiler, private injector: Injector) {
}
async ngOnInit(): Promise<void> {
await this.loadComponent();
}
async loadComponent(): Promise<void> {
const { TestComponent, TestModule } = await import('./test');
const moduleFactory = await this.loadModuleFactory(TestModule);
const moduleRef = moduleFactory.create(this.injector);
const factory = moduleRef.componentFactoryResolver.resolveComponentFactory(TestComponent);
this.containerRef.createComponent(factory);
}
private async loadModuleFactory(moduleFactory: Type<TestModule>): Promise<NgModuleFactory<TestModule>> {
if (moduleFactory instanceof NgModuleFactory) {
return moduleFactory;
} else {
return await this.compiler.compileModuleAsync(moduleFactory);
}
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The app.module.ts is included here for completeness.
After compiling all these code snippets, the text within the p tags is not being displayed.