Angular 依赖注入的一个常见错误 NullInjectorError, No provider for XXX
生活随笔
收集整理的這篇文章主要介紹了
Angular 依赖注入的一个常见错误 NullInjectorError, No provider for XXX
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
測(cè)試代碼:
export abstract class GreetingService {abstract greet(name: string): string;}加了@Injectable注解的實(shí)現(xiàn)類(lèi):
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!');} }試圖通過(guò)構(gòu)造函數(shù)參數(shù)的方式注入:
錯(cuò)誤消息:
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區(qū)域里,為GreetingService維護(hù)具體的實(shí)現(xiàn)類(lèi):
providers: [{ provide: JerrySandBoxService },{ provide: GreetingService, useClass: EnglishGreetingService}]問(wèn)題即可解決:
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Angular 依赖注入的一个常见错误 NullInjectorError, No provider for XXX的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CPU基础知识CPU的组成 运算器、控制
- 下一篇: Angular getOrCreateI