NullInjectorError: R3InjectorError No provider for AlertPanelComponent

NullInjectorError: R3InjectorError No provider for AlertPanelComponent

错误信息:

ERROR NullInjectorError: R3InjectorError(AppModule)[AlertPanelComponent -> AlertPanelComponent -> AlertPanelComponent]: NullInjectorError: No provider for AlertPanelComponent! Angular

我不明白,我只是想从警报中导入我的 AlertPanelComponent-panel.component。

在 Whosebug 上搜索时,这个错误似乎很广泛。我已经把这个放在我的 app.module.

app.component.ts

import {AlertClass} from './models/alert-class.model';
...
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, DoCheck {
    ...
    constructor( private restService:RestService,
        private sanitizer: DomSanitizer,
        private router:Router, 
        private alertPanelComponent:AlertPanelComponent ){
    }
    ...
}

app.module.ts

import { AlertPanelComponent } from './alert-panel/alert-panel.component';
...
@NgModule({
    declarations: [
        AlertPanelComponent,
        ...
    ],
    ...
})
export class AppModule { }

应用-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, 
    Routes,
    PreloadAllModules} from '@angular/router';
import {LoginComponent} from './login/login.component';
import {AlertPanelComponent} from './alert-panel/alert-panel.component';
import {WebCamComponent} from './web-cam/web-cam.component';
const routes: Routes = [
    {path: '',component: LoginComponent},
    {path: 'alert-panel',component: AlertPanelComponent},
    {path: 'webcam', component: WebCamComponent}
];

@NgModule({
    imports: [RouterModule.forRoot(routes)
    ],
    exports: [RouterModule]
})
export class AppRoutingModule { }

首先,你是通过CLI生成组件的吗? 因为它通常会做一些导入工作,请检查一下。

其次,你能告诉我你的应用程序-routing.module.ts,这是 nullInjectorError 的主要候选者。

将 AlertPanelComponent 添加到您的应用程序组件构造函数会强制您将其作为提供程序添加到您的应用程序模块中。

组件不会那样做,或者将其更改为提供者,或者在您的情况下,根据您的代码判断,您实际上没有在应用程序组件中使用 AlertPanelComponent