Javascript Angular 6 错误“NullInjectorError:没有路由器提供程序!”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51419602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:50:04  来源:igfitidea点击:

Angular 6 Error "NullInjectorError: No provider for Router!"

javascriptasp.netangularfrontend

提问by Fenouille

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 :

我目前正在做一个项目,我需要用户填写一个角度表单,然后将其发送到我后端的路由以处理数据。后端在 ASP.NET 中,我已经有一个正在运行的 HTML 中的功能表单:

<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

HTML 渲染

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 6 中用这个结果做同样的事情,但是当我想将路由“SendNotification”分配给我的“提交”按钮时,我收到以下错误:

Angular Rendering + Error

角度渲染 + 错误

enter image description here

在此处输入图片说明

notification-form.component.html

通知-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 :

一旦我添加[routerLink]或添加私有构造函数,就会发生错误:

 constructor(private router: Router) {}

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

到我的notification-form.component.ts. 我已经尝试了几种解决方案,例如添加HttpClientModule到我的app.module.ts但没有任何效果。

Is there something I'm doing wrong?

有什么我做错了吗?

Thank you in advance for your time!

提前感谢您的时间!

UPDATE:

更新:

app.module.ts

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

回答by coder

First import RouteModulein app.module.ts

首先进口RouteModuleapp.module.ts

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

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

并像下面那样使用它:(您只需导入RouterModule但还需要添加forRoot([])。)

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

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

如果您有任何路线,请使用它们,如下所示。来自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>

并在您的主要 Component ( app.component.html) 添加<router-outlet></router-outlet>

Hope this will help you!

希望能帮到你!

回答by Fenouille

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

如果有人使用 npm link(s),下面的工作:

In .angular-cli.jsonadd/replace:

.angular-cli.json添加/替换中:

"defaults": {
    "styleExt": "css",
    "component": {},
    "build": {
        "preserveSymlinks": true
    }
}

回答by Juan

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

你需要添加一个 <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:

标签<router-outlet></router-outlet>是您的应用程序将呈现不同路由的地方。例如,在 app.component.html 中,您可以拥有:

<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:

将这个添加到你的 app.module.ts 中的导入数组中:

RouterModule.forRoot([
      { path: 'SendNotification', component: YourComponent }

回答by Wictor Chaves

In my case, I only put:

就我而言,我只输入:

<base href="/">

In my headtag in the index.htmlfile.

在我headindex.html文件中的标签中。

...
<head>
  ...
  <title>Name of page</title>
  <base href="/">
</head>
...

回答by Ben Winding

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

对于那些也在苦苦挣扎的人,从 Angular 编译器发出的神秘/无用的错误消息,请确保你在某处有这个:

RouterModule.forRoot([])

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

我只使用RouterModule.forChild([]),在其中一个模块中添加 forRoot() 修复了错误。

回答by Gopala raja naika

Please check this linkhttps://angular.io/api/router/RouterStateSnapshot

请检查此链接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);
   //...
 }
}