angulartypescriptangular-injector

NullInjectorError: R3InjectorError No provider for AlertPanelComponent


Error message:

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

I do not understand this, I am just trying to import my AlertPanelComponent from the alert-panel.component.

This error seems to be very broad when searching on stackOverflow. I have put this in my 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 { }

app-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 { }

Solution

  • First, did you generate the component through the CLI? because that usually do some import work, check that.

    Second, can you show me your app-routing.module.ts, this is a prime candidate for nullInjectorError.

    Adding AlertPanelComponent to your app-component constructor imposes that you add it as a provider in your app-module.

    Components do not behave that way, either change it to a provider, or in your case, judging by your code, you have no use of actually AlertPanelComponent in your app-component