尝试将路由器注入app.component.ts时发生错误

时间:2018-07-31 03:56:14

标签: javascript angular

我无法通过调用“专用路由器:路由器”将路由器注入到app.component.ts文件的构造函数中。

它给了我以下错误: 错误:“ StaticInjectorError(AppModule)[AppComponent->路由器]:   StaticInjectorError(平台:核心)[AppComponent->路由器]:     NullInjectorError:路由器没有提供者!”

但是当我删除注入时,页面运行良好,但是我无法使用导航功能加载到其他组件中。

这就是我所拥有的

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MessageParser]
})


export class AppComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit() {}

  goToLobby() {
    this.router.navigate(['lobby']);
  }
}

app.component.html

<button (click)="goToLobby()">Go to lobby</button>

<router-outlet></router-outlet>

app-routing.module.ts

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

import { MainComponent } from './main/main.component';
import { LobbyComponent } from './lobby/lobby.component';
import { GameComponent } from './game/game.component';

const appRoutes: Routes = [
  { path: '', component: MainComponent },
  { path: 'lobby', component: LobbyComponent },
  { path: 'game', component: GameComponent }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule {}

1 个答案:

答案 0 :(得分:1)

从AppRoutingModule中的导出中删除RouterModule

var frate = 10;
var elliX = 500;
var elliY = 400;

function setup() {
    createCanvas(100, 100);
    frameRate(frate);
}

function draw() {
    elliX = (random(0,100));
    elliY = (random(0,100));
    ellipse(elliX, elliY, 30);
}