简体   繁体   中英

NullInjectorError: R3InjectorError(AppModule) After adding providers

After adding provider also getting the NullInjectorError in Angular 14

Code shown below

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

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

In providers array you were passing config object instead of dependency, that is why you getting NullInjection error.

One way to fix is you can create new injection token and pass value using useValue method, then pass CONFIG dependency to LogService deps

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 {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM