Angular 6 Error “NullInjectorError: No provider fo

2020-08-23 04:21发布

I'm currently working on a project where I need the user to fill out an angular form and then send it to a route in my backend to process the data. The backend is in ASP.NET and I already have a functional form in HTML that's working :

<body>
<h2 style="text-align:center">Push notification test</h2>
<form style="align-content:center" action="SendPushNotification" method="post">
    <div>
        <fieldset>
            <legend> Informations </legend>
            <label> Notification name : </label>
            <input name="notificationName" id="notificationName" type="text" value="Bonjour" />
        </fieldset>
        <br />
        <fieldset>
            <label> Server Key : </label>
            <input name="serverKey" id="serverKey" type="text" value="AAAAuTv1XVQ:APA91bHsgOmK-quki_rRehRhON9c_y9INocubgru6_jPePiE_Zt5iVXfJ-XD43RubfIY5WEoIpFEyziByfeNRsoIlpeNi693bGZYfjjb7ULDx23sRzHQcYLCgl7y3vn-K9X8hrmQhw1oY6lSTml2aqzoi8GGBIeZYA" />
        </fieldset>
        <br />
        <fieldset>
            <label> To mobile user : </label>
            <select name="selectMobile" id="selectMobile" style="width:400px" name="mobileUser">
                <option>Select Mobile User</option>
            </select>
        </fieldset>
        <br />
        <fieldset>
            <label> To topic : </label>
            <input name="topicName" id="topicName" type="text" value="news" />
        </fieldset>
        <br />
        <fieldset>
            <label> Message : </label>
            <textarea name="notificationMessage" id="notificationMessage" cols="40" rows="5">Comment tu vas toi ?</textarea>
        </fieldset>
        <br />
        <input type="submit" value="Send Notification" />
    </div>
</form>

HTML Rendering

enter image description here

So I'm trying to do the same thing in Angular 6 with this result but when I want to assign the route "SendNotification" to my "Submit" button I get the following error :

Angular Rendering + Error

enter image description here

notification-form.component.html

<button [routerLink]="['SendNotification']" type="submit" class="btn btn-success" [disabled]="!notificationForm.form.valid">Submit</button>

The error occurs as soon as I add [routerLink] or add a private constructor :

 constructor(private router: Router) {}

to my notification-form.component.ts. I have already tried several solutions like adding HttpClientModule to my app.module.ts but nothing works.

Is there something I'm doing wrong?

Thank you in advance for your time!

UPDATE:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { NotificationFormComponent } from './notification-form/notification-form.component';

@NgModule({
  imports: [
BrowserModule,
HttpClientModule,
FormsModule,
RouterModule
],  
declarations: [
AppComponent,
NotificationFormComponent
],
providers: [],
bootstrap: [AppComponent]
})

export class AppModule { }

6条回答
ら.Afraid
2楼-- · 2020-08-23 04:48

First import RouteModule in app.module.ts

import { RouterModule, Routes } from '@angular/router';

And use it like below: (You only import RouterModule but need to add forRoot([]) also.)

imports: [
    RouterModule.forRoot([])
    // other imports here
  ]

If you have any routes use them like below. This sample code from Angular DOC

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

And in your main Component (app.component.html) add <router-outlet></router-outlet>

Hope this will help you!

查看更多
Explosion°爆炸
3楼-- · 2020-08-23 04:48

In case someone is using npm link(s), the following does the job:

In .angular-cli.json add/replace:

"defaults": {
    "styleExt": "css",
    "component": {},
    "build": {
        "preserveSymlinks": true
    }
}
查看更多
看我几分像从前
4楼-- · 2020-08-23 04:54

Please check this link https://angular.io/api/router/RouterStateSnapshot

import { Component, OnInit } from '@angular/core';
import { RouterState, RouterStateSnapshot, Router } from '@angular/router'; 

@Component({
  templateUrl:'template.html'
})
export class MyComponent {
  constructor(router: Router) {
   const state: RouterState = router.routerState;
   const snapshot: RouterStateSnapshot = state.snapshot;
   console.log(state);
   console.log(snapshot);
   //...
 }
}
查看更多
女痞
5楼-- · 2020-08-23 04:55

In my case, I only put:

<base href="/">

In my head tag in the index.html file.

...
<head>
  ...
  <title>Name of page</title>
  <base href="/">
</head>
...
查看更多
虎瘦雄心在
6楼-- · 2020-08-23 05:00

For those also struggling, with the cryptic/unhelpful error messages from the Angular compiler, make sure you have this somewhere:

RouterModule.forRoot([])

I was only using RouterModule.forChild([]), adding a forRoot() in one of the modules fixed the error.

查看更多
啃猪蹄的小仙女
7楼-- · 2020-08-23 05:01

You need to add a <router-outlet></router-outlet>

The tag <router-outlet></router-outlet> is the place where your app is going to render the different routes. For example, in the app.component.html you can have:

<header>
    <bt-toolbar></bt-toolbar>
</header>

<main>
    <router-outlet></router-outlet>
</main>

With this template I have a top bar always visible and below is the content of the diferent routes.

Add to your app.module.ts this in the imports array:

RouterModule.forRoot([
      { path: 'SendNotification', component: YourComponent }
查看更多
登录 后发表回答