NullInjectorError:R3InjectorError 没有 AlertPanelComponent 的提供程序

Rya*_*yan 2 typescript angular angular-injector

错误信息:

错误 NullInjectorError:R3InjectorError(AppModule)[AlertPanelComponent -> AlertPanelComponent -> AlertPanelComponent]:NullInjectorError:没有 AlertPanelComponent 的提供程序!角

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

在 stackOverflow 上搜索时,这个错误似乎非常广泛。我已将其放入我的 app.module 中。

应用程序组件.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 ){
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

应用程序模块.ts

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

应用程序路由.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 { }
Run Code Online (Sandbox Code Playgroud)

Hay*_*hem 6

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

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

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

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

  • 您的意思是您更新了 app-routing.module.ts 以包含警报面板组件,对吧? (2认同)
  • 为什么要在应用程序组件构造函数中添加 AlertPanelComponent? (2认同)
  • 想一想,要跨组件共享变量,最好使用 Angular Services 而不是导入另一个组件。WebStorage API 很有用,但它似乎不如 Angular Services 有用。 (2认同)
  • 根据情况,对于某些数据,我使用角度服务,对于其他数据,我只使用 localStorage,话虽如此,这并不是唯一的两个选择 (2认同)