A common error of Angular dependency injection NullInjectorError, No provider for XXX

Test code:

export abstract class GreetingService {
    abstract greet(name: string): string;
 }

Implementation class annotated with @Injectable:

import { Injectable } from '@angular/core';
import { GreetingService } from './greeting.service';

@Injectable({ providedIn: 'root'})
export class EnglishGreetingService extends GreetingService {
   greet(name: string): string {
      return 'Hello ' + name;
   }
   constructor(){
      super();
      console.log('English class created!');
   }
}

Attempt to inject through constructor parameters:

wrong information:

core.js:6241 ERROR NullInjectorError: R3InjectorError(AppModule)[GreetingService -> GreetingService -> GreetingService]: 
  NullInjectorError: No provider for GreetingService!
    at NullInjector.get (http://localhost:4201/vendor.js:8310:27)
    at R3Injector.get (http://localhost:4201/vendor.js:22317:33)
    at R3Injector.get (http://localhost:4201/vendor.js:22317:33)
    at R3Injector.get (http://localhost:4201/vendor.js:22317:33)
    at NgModuleRef$1.get (http://localhost:4201/vendor.js:39618:33)
    at Object.get (http://localhost:4201/vendor.js:37352:35)
    at getOrCreateInjectable (http://localhost:4201/vendor.js:12112:39)
    at Module.ɵɵdirectiveInject (http://localhost:4201/vendor.js:26132:12)
    at NodeInjectorFactory.AppComponent_Factory [as factory] (http://localhost:4201/main.js:122:289)
    at getNodeInjectable (http://localhost:4201/vendor.js:12257:44)

Solution

In the providers area of ​​the module, maintain specific implementation classes for GreetingService:

providers: [{ provide: JerrySandBoxService },
  { provide: GreetingService, useClass: EnglishGreetingService}]

The problem can be solved:

To get more original articles by Jerry, please follow the public account "Wang Zixi":

Guess you like

Origin blog.csdn.net/i042416/article/details/108640658