角度错误:没有ActivatedRoute的提供者

时间:2018-02-28 22:11:15

标签: angular angular-activatedroute

我使用的是最新的角度5,我正在使用以下异常

ERROR Error: StaticInjectorError(AppModule)[AppComponent -> ActivatedRoute]: 
  StaticInjectorError(Platform: core)[AppComponent -> ActivatedRoute]: 
    NullInjectorError: No provider for ActivatedRoute!
    at _NullInjector.get (core.js:1002)
    at resolveToken (core.js:1300)
    at tryResolveToken (core.js:1242)
    at StaticInjector.get (core.js:1110)
    at resolveToken (core.js:1300)
    at tryResolveToken (core.js:1242)
    at StaticInjector.get (core.js:1110)
    at resolveNgModuleDep (core.js:10854)
    at NgModuleRef_.get (core.js:12087)
    at resolveDep (core.js:12577)

app.module.ts如下所示 从'@ angular / router'导入{Routes,RouterModule};

@NgModule({
  declarations: [
    AppComponent,
    OptyDetailsComponent,
    GlobalNavbarComponent
  ],
  imports: [
    BrowserAnimationsModule,
    BrowserModule,
    HttpModule,
    HttpClientModule,
    FlexLayoutModule,
    FormsModule,
    MatButtonModule,
    MatInputModule
    RouterModule
  ],
  entryComponents: [
  ], 
  providers: [
    DataStoreService,
    DataObjectsOscService,
    AdobeSignService,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:26)

为了能够在角度元素中提供ActivatedRoute,您需要将调用RouterModule.forRoot的结果导入到根模块(AppModule)中。这是因为RouterModule.forRoot返回的模块包括ActivatedRoute实例的提供程序等。

所以基本上你需要在根模块中的导入中添加以下内容:

@NgModule({
  ...
  imports: [
    ...
    // Remark: because you havent defined any routes, I have to pass an empty
    // route collection to forRoot, as the first parameter is mandatory.
    RouterModule.forRoot([]),
    ...
  ],
  ...
})
export class AppModule { }

但说实话,尽管您没有为根模块定义任何路由,但使用ActivatedRoute有点奇怪。

有关详细信息,请参阅:

ActivatedRoute provider source

RouterModule.forRoot() source