美文网首页SAP
Angular依赖注入的一个常见错误NullInjectorEr

Angular依赖注入的一个常见错误NullInjectorEr

作者: _扫地僧_ | 来源:发表于2020-12-06 09:49 被阅读0次

    测试代码:

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

    问题即可解决:

    相关文章

      网友评论

        本文标题:Angular依赖注入的一个常见错误NullInjectorEr

        本文链接:https://www.haomeiwen.com/subject/pvylyktx.html