在角度2中进行参数路由时,构造函数注入会阻止页面加载

问题描述 投票:0回答:1

emp-list.component.ts

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


@Component({
       selector:'emp-list',
       template:`
                <ul>
                    <li (click)="onSelect(emp)"  *ngFor="let emp of employees">
                       <span> {{emp.id}}</span>----<span>{{emp.name}}</span>
                    </li>
                </ul>
       `
})


export class  EmployeeListComponent 
{
    constructor(private router:Router) { }

    employees = [
        {"id":12,"name":"Srikant"},
        {"id":13,"name":"Sriram"},
        {"id":14,"name":"Sushant"}
    ]      
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',

  template: ` 
             <emp-list></emp-list>
  `   
})
export class AppComponent {}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Router } from '@angular/router';
import { AppComponent } from './app.component';
import {EmployeeListComponent} from './Employees/emp-list.component';
import { EmployeeParticularComponent } from './Employees/emp-details.component';

@NgModule({
  imports: [BrowserModule,

  ],
  declarations: [AppComponent,EmployeeListComponent],
  bootstrap: [AppComponent]
})
export class AppModule { 


}

When removing the constructor, everything works fine.
angular
1个回答
0
投票

RouterRouterModule中定义,但你没有在你的app.module.ts中导入它。

您应该在控制台中收到以下错误:

错误:StaticInjectorError [Router]:StaticInjectorError [Router]:NullInjectorError:没有路由器的提供者!

将其添加到导入列表中。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot([{ path: "", component: AppComponent}])
   ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

看看我工作的stackblitz示例。带有router参数的构造函数位于app.component.ts文件中。

© www.soinside.com 2019 - 2024. All rights reserved.