[英]ERROR NullInjectorError: R3InjectorError(AppModule)
[英]NullInjectorError: R3InjectorError(AppModule) After adding providers
添加提供程序后,在 Angular 14 中也会出现 NullInjectorError
代码如下所示
app.module.ts
import { LogService } from './services/log.service';
import { LogType, Config } from './interface/config';
import { loggerServiceFactory } from './logfactory';
export const config = {
apiUrl: 'http://localhost:3000',
logType: LogType.Default
}
providers: [
{provide: LogService, useFactory: loggerServiceFactory, deps:[config]}
],
loggerServiceFactory
import { AppConfig, LogType } from "./interface/config";
import { ClientService } from "./services/client.service";
import { LogService } from "./services/log.service";
export const loggerServiceFactory = (config: AppConfig) => {
if(config.logType === LogType.Client) {
return new ClientService();
}
return new LogService();
}
日志服务
import { Injectable } from '@angular/core';
@Injectable()
export class LogService {
protected id = 0;
constructor() {
this.id = Math.random() * 100;
console.log(`LoggerService ${this.id} created`)
}
log(message: string) {
console.log(`LoggerService ${this.id} log: ${message}`);
}
}
app.component.ts
constructor(private log: LogService){
this.log.log('App component constructor');
}
在提供者数组中,您传递的是配置 object 而不是依赖项,这就是您收到 NullInjection 错误的原因。
一种解决方法是您可以创建新的注入令牌并使用 useValue 方法传递值,然后将 CONFIG 依赖项传递给 LogService 部门
import { InjectionToken, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { loggerServiceFactory, LogServiceToken } from './logfactory';
import { LogService } from './logservice';
export const config = {
apiUrl: 'http://localhost:3000',
logType: 'log',
};
export const CONFIG = new InjectionToken<typeof config>('CONFIG');
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, HelloComponent],
providers: [
{ provide: CONFIG, useValue: config },
{
provide: LogService,
useFactory: (config) => {
return loggerServiceFactory(config);
},
deps: [CONFIG],
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.