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

时间:2018-02-27 17:12:20

标签: angular

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.

1 个答案:

答案 0 :(得分: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文件中。