簡體   English   中英

Angular 6 錯誤“NullInjectorError:沒有路由器提供程序!”

[英]Angular 6 Error "NullInjectorError: No provider for Router!"

我目前正在做一個項目,我需要用戶填寫一個角度表單,然后將其發送到我后端的路由以處理數據。 后端在 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”分配給我的“提交”按鈕時,我收到以下錯誤:

角度渲染 + 錯誤

在此處輸入圖片說明

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

首先進口RouteModuleapp.module.ts

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 )中添加<router-outlet></router-outlet>

希望能幫到你!

對於那些也在苦苦掙扎的人,從 Angular 編譯器發出的神秘/無用的錯誤消息,請確保你在某處有這個:

RouterModule.forRoot([])

我只使用RouterModule.forChild([]) ,在其中一個模塊中添加一個 forRoot() 修復了錯誤。

如果您正在使用

RouterModule.forChild(routes)

嘗試將其替換為

RouterModule.forRoot(routes)

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

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

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

你需要添加一個<router-outlet></router-outlet>

標簽<router-outlet></router-outlet>是你的應用渲染不同路由的地方。 例如,在 app.component.html 中,您可以擁有:

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

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

使用這個模板,我有一個始終可見的頂部欄,下面是不同路線的內容。

將這個添加到你的 app.module.ts 中的導入數組中:

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

就我而言,我只輸入:

<base href="/">

index.html文件中的head標記中。

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

請檢查此鏈接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);
   //...
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM