在Angular应用中,当出现错误消息"NullInjectorError: No provider for ..."时,通常是由于未正确配置或提供所需的依赖项导致的。以下是一些常见的解决方法。
import { NgModule } from '@angular/core';
import { SomeService } from './some-service';
@NgModule({
providers: [SomeService]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { SomeModule } from './some-module';
@NgModule({
imports: [SomeModule]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SomeModule } from './some-module';
@NgModule({
imports: [CommonModule, SomeModule]
})
export class AppModule { }
import { Component, OnInit } from '@angular/core';
import { SomeService } from './some-service';
@Component({
selector: 'app-some-component',
templateUrl: './some-component.component.html',
styleUrls: ['./some-component.component.css']
})
export class SomeComponent implements OnInit {
constructor(private someService: SomeService) { }
ngOnInit() {
// 使用SomeService
}
}
通过检查提供者的配置、导入模块以及正确使用依赖注入标记,你应该能够解决"NullInjectorError: No provider for ..."错误。