Une erreur courante d'injection de dépendance angulaire NullInjectorError, aucun fournisseur pour XXX

Code de test:

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

Classe d'implémentation annotée avec @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!');
   }
}

Tentative d'injection via les paramètres du constructeur:

mauvaise 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

Dans la zone des fournisseurs du module, maintenez des classes d'implémentation spécifiques pour GreetingService:

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

Le problème peut être résolu:

Pour obtenir plus d'articles originaux de Jerry, veuillez suivre le compte public "Wang Zixi":

Je suppose que tu aimes

Origine blog.csdn.net/i042416/article/details/108640658
conseillé
Classement