【发布时间】:2022-03-09 20:59:22
【问题描述】:
我有一个 Angular 应用程序,它有 3 个库。一个是共享库,另外两个是用作微应用程序的库,我使用角度元素来渲染这两个库。共享库具有注入 HttpClient、DecimalPipe 等 Angular 类的服务。我收到静态空注入器错误 (NullInjectorError: R3InjectorError[CounterService -> CounterService -> CounterService -> CounterService -> DecimalPipe]) 共享库模块在导入部分有 HttpClientModule、Common 模块、浏览器模块。如果我在共享库模块中创建另一个服务,它可以与 DI 一起正常工作。
@NgModule({
declarations: [SharedLibComponent],
imports: [
BrowserModule,
CommonModule,
HttpClientModule
],
exports: [SharedLibComponent],
providers: [HttpClient, DecimalPipe]
})
export class SharedLibModule { }
@Injectable({
providedIn: 'platform'
})
export class CounterService {
count: number = 0;
constructor(private _decimalPipe: DecimalPipe) {
console.log('inside constructor');
}
increment() {
this.count = this.count + 1;
}
decrement() {
this.count = this.count - 1;
}
}
这里我选择providedIn 作为平台,因为它是微应用。我只需要一个跨多个微应用的组件实例,我可以通过将微应用创建为带有 shell 项目的库来实现。
@NgModule({
declarations: [
MyLibComponent,
DashboardComponent,
MyAccountComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [
BrowserModule,
MyLibRoutingModule,
HttpClientModule,
SharedLibModule
]
})
export class MyLibModule implements DoBootstrap {
constructor(private injector: Injector) {
console.log('inside my lib module constructor');
}
ngDoBootstrap() {
console.log("PMB Module: Entered ngDoBootstrap...");
const myElementExists = !!customElements.get("pmb-lib");
if (!myElementExists) {
const appElement = createCustomElement(MyLibComponent, {
injector: this.injector
});
customElements.define("my-lib", appElement);
}
console.log("My lib Module: Completed ngDoBootstrap...");
}
}
// If there is already a platform, reuse it, otherwise create a new one
(getPlatform() || platformBrowser()).bootstrapModule(MyLibModule).catch(err => console.log(err));
非常感谢任何想法或帮助。
【问题讨论】:
标签: angular