【问题标题】:Angular 6 Error "NullInjectorError: No provider for Router!"Angular 6 错误“NullInjectorError:没有路由器提供程序!”
【发布时间】:2018-12-27 09:52:58
【问题描述】:

我目前正在做一个项目,我需要用户填写一个角度表单,然后将其发送到我后端的路由以处理数据。后端在 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 渲染

所以我试图在 Angular 6 中用这个结果做同样的事情,但是当我想将路由“SendNotification”分配给我的“提交”按钮时,我收到以下错误:

角度渲染 + 错误

notification-form.component.html

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

我添加[routerLink] 或添加私有构造函数后立即发生错误:

 constructor(private router: Router) {}

致我的notification-form.component.ts。 我已经尝试了几种解决方案,例如将HttpClientModule 添加到我的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 { }

【问题讨论】:

  • 你是否在 app.module.ts 中包含了路由器模块?
  • 是的,我会用我的 app.module.ts 更新姿势

标签: javascript asp.net angular frontend


【解决方案1】:

首先在app.module.ts中导入RouteModule

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

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

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

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

并在您的主要组件 (app.component.html) 中添加 &lt;router-outlet&gt;&lt;/router-outlet&gt;

希望对您有所帮助!

【讨论】:

  • 嗨!感谢您的时间,我尝试了您的解决方案,但现在我收到此错误:zone.js:665 Unhandled Promise reject: No base href set。请提供 APP_BASE_HREF 令牌的值或向文档添加基本元素。 ;区域: ;任务:Promise.then;值:错误:未设置基本 href。请提供 APP_BASE_HREF 令牌的值或向文档添加基本元素。
  • 您是否将&lt;router-outlet&gt;&lt;/router-outlet&gt; 添加到app.component.html 中?
  • 并且还要检查你的 index.html 在head 标签中有&lt;base href="/"&gt;
  • 是的,我添加了一个,而我的 index.html 有一个:/
  • 嘿,你拯救了我的一天。非常感谢!
【解决方案2】:

对于那些还在苦苦挣扎的人,来自 Angular 编译器的神秘/无用的错误消息,请确保你在某个地方有这个:

RouterModule.forRoot([])

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

【讨论】:

    【解决方案3】:

    如果你正在使用

    RouterModule.forChild(routes)

    尝试替换为

    RouterModule.forRoot(routes)

    【讨论】:

    • 谢谢!它对我有用:)
    【解决方案4】:

    如果有人正在使用 npm 链接,则以下操作可以完成:

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

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

    【讨论】:

      【解决方案5】:

      就我而言,我只说:

      <base href="/">
      

      index.html 文件中我的head 标记中。

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

          您需要添加&lt;router-outlet&gt;&lt;/router-outlet&gt;

          标签&lt;router-outlet&gt;&lt;/router-outlet&gt; 是您的应用要渲染不同路线的地方。例如,在 app.component.html 中你可以有:

          <header>
              <bt-toolbar></bt-toolbar>
          </header>
          
          <main>
              <router-outlet></router-outlet>
          </main>
          

          有了这个模板,我有一个始终可见的顶栏,下面是不同路线的内容。

          在导入数组中添加到您的 app.module.ts 中:

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

          【讨论】:

          • 嗨!我应该在哪里添加它?
          猜你喜欢
          • 1970-01-01
          • 2019-06-22
          • 1970-01-01
          • 2022-11-25
          • 1970-01-01
          • 2016-01-16
          • 2020-11-30
          • 1970-01-01
          • 2019-10-20
          相关资源
          最近更新 更多