Angular:如果未在任何提供程序中声明路由器,如何将路由器注入组件中?

时间:2018-10-30 10:22:40

标签: angular angular-routing

假设我们具有以下组件:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  constructor(private router: Router) { }
}

为了将某些东西注入到组件中,我们必须在组件/超级组件的providers数组中或在模块中声明它。由于Router尚未通过两种方法声明,因此如何在构造函数中使用它?

是因为它是Angular中默认提供的吗?

1 个答案:

答案 0 :(得分:1)

RouterRouterModulegithub repo提供:

export const ROUTER_PROVIDERS: Provider[] = [
  Location,
  {provide: UrlSerializer, useClass: DefaultUrlSerializer},
  {
    provide: Router,
    useFactory: setupRouter,
...

static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule> {
    return {
      ngModule: RouterModule,
      providers: [
        ROUTER_PROVIDERS,
...