Angular 2: Bootstrap at least one component before

2020-04-04 14:33发布

问题:

I get this error in my RC5 app:

Promise rejection: Bootstrap at least one component before injecting Router.

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

app.module.ts:

@NgModule({
  imports: [
    BrowserModule,
    routing,
    SharedModule.forRoot()
  ],
  declarations: [
    AppComponent, 
    ErrorComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

shared.module.ts:

@NgModule({
  imports: [CommonModule, RouterModule, HttpModule, FormsModule, ReactiveFormsModule],
  declarations: [TranslatePipe, DateToStringPipe, HeaderComponent, FooterComponent],
  exports: [TranslatePipe, DateToStringPipe, CommonModule, FormsModule, ReactiveFormsModule, HeaderComponent, FooterComponent]
})
export class SharedModule {

  static forRoot(): ModuleWithProviders {

    return {
      ngModule: SharedModule,
      providers: [
        FeedbackService,
        CookieService,
        AuthService,
        LoggerService,
        RouteGuard,
        {
          provide: TranslateLoader,
          useFactory: (http: Http) => new TranslateStaticLoader(http, 'app/languages', '.json'),
          deps: [Http]
        },
        TranslateService,
        SearchService,
        SharedComponent,
        HeaderComponent,
        FooterComponent
      ]
    };

  }

}

@NgModule({
  exports: [ SharedModule],
  providers: []
})
export class SharedRootModule {}

app.component.ts:

export class AppComponent extends SharedComponent implements OnInit {

constructor(
    _feedbackService: FeedbackService,
    _loggerService: LoggerService,
    _translateService: TranslateService,
    _authService: AuthService,
    _router: Router
) {

    super(
        _feedbackService,
        _loggerService,
        _translateService,
        _authService,
        _router
    );

}

and finally shared.component.ts:

constructor(
    protected _feedbackService: FeedbackService,
    protected _loggerService: LoggerService,
    protected _translateService: TranslateService, 
    protected _authService: AuthService, 
    protected _router: Router
) {

}

I tried using AppComponent without the extension from SharedComponent like this:

export class AppComponent implements OnInit {

constructor(){
}

but that still produces the same problem.

回答1:

Angular thinks it is not necessary to inject Router in the Module level, it is reasonable you inject the Router after at least one component is loaded. I suspect at least one of your services must be injecting Router, which is provided to the loaded Module, which causes this error. What you can do is to inject the service that uses the Router to the app component, so at least one component is loaded first, and all your sub-components will inherit the service from the app component.



标签: angular