0

错误信息:

错误 NullInjectorError: R3InjectorError(AppModule)[AlertPanelComponent -> AlertPanelComponent -> AlertPanelComponent]: NullInjectorError: No provider for AlertPanelComponent!角

我不明白这一点,我只是想AlertPanelComponent从 alert-panel.component 导入我的。

在 stackOverflow 上搜索时,此错误似乎非常广泛。我已经把它放在了我的 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 { }

应用程序路由.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 { }
4

1 回答 1

2

首先,您是否通过 CLI 生成了组件?因为那通常会做一些导入工作,请检查一下。

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

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

组件不会以这种方式运行,要么将其更改为提供程序,要么在您的情况下,根据您的代码判断,您实际上在应用程序组件中没有使用 AlertPanelComponent

于 2021-08-16T13:26:19.750 回答