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


Why logService does not have {providerIn: 'root'} or you're injected service in providers array of AppModule?

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


Good catch, plus one! Also, seems like OP have AppConfig type for config, let's wait for OP to respond

Thanks @PankajParkar bro. Since he declared const config I assumed It should be type of config, However let him confirm
