Código de prueba:
export abstract class GreetingService {
abstract greet(name: string): string;
}
Clase de implementación anotada con @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!');
}
}
Intente inyectar a través de los parámetros del constructor:
información errónea:
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)
Solución
En el área de proveedores del módulo, mantenga clases de implementación específicas para GreetingService:
providers: [{ provide: JerrySandBoxService },
{ provide: GreetingService, useClass: EnglishGreetingService}]
El problema se puede solucionar:
Para obtener más artículos originales de Jerry, siga la cuenta pública "Wang Zixi":