测试代码:
export abstract class GreetingService {
abstract greet(name: string): string;
}
加了@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!');
}
}
试图通过构造函数参数的方式注入:
错误消息:
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)
解决办法
在module的providers区域里,为GreetingService维护具体的实现类:
providers: [{ provide: JerrySandBoxService },
{ provide: GreetingService, useClass: EnglishGreetingService}]
问题即可解决:
网友评论