Angular 2从RC4升级到RC5,错误:在注入路由器之前引导至少一个组件

时间:2016-08-11 17:59:55

标签: angular router

尝试使用路由器3.0.0-rc.1升级到2.0.0-rc.5。

我已经按照文档中的升级说明(从RC4移动,这对我来说很好)。我收到了这个错误,不知道发生了什么:

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

Zone: <root> ; Task: Promise.then ; Value: Error: Bootstrap at least one component before injecting Router.
at     setupRouter     node_modules/@angular/router/src/common_router_providers.js:21:15)
at NgModuleInjector .get (AppModule .ngfactory .js:227:57)
at NgModuleInjector .AppModuleInjector .createInternal (AppModule .ngfactory .js:309:55)
at NgModuleInjector .create

/node_modules/@angular/core/src/linker/ng_module_factory .js:91:76)
at NgModuleFactory .create /node_modules/@angular/core/src/linker/ng_module_factory .js:75:18)
/node_modules/@angular/core/src/application_ref .js:341:43)
at ZoneDelegate .invoke 
/node_modules/zone .js/dist/zone .js:323:29)
at Object .onInvoke 
node_modules/@angular/core/src/zone/ng_zone_impl.js:53:41)
at ZoneDelegate
/node_modules/zone.js/dist/zone .js:322:35)
at Zone.run /node_modules/zone .js/dist/zone .js:216:44)

1 个答案:

答案 0 :(得分:3)

问题:https://github.com/angular/angular/issues/11660

解决方案:当您将路由器注入需要路由器的服务时,就像这样

@NgModule({
    imports : [
        BrowserModule
    ],
    providers : [
        {
        provide : Http,
        useFactory: (
            xhrBackend: XHRBackend, 
            requestOptions: RequestOptions,
            router: Router, <-- our problem
            constantsService:ConstantsService, 
            loaderComponentHelper: LoaderComponentHelper
        ) => new HttpInterceptor(xhrBackend, requestOptions, router, constantsService, loaderComponentHelper),
        deps: [XHRBackend, RequestOptions, Router, ConstantsService, LoaderComponentHelper],
    },
    {
        provide : AuthHttp, 
        useFactory: (http: Http, authService: AuthService, constantsService: ConstantsService) => {
            return new AuthHttp(http, authService, constantsService);
        },
        deps : [Http, AuthService, ConstantsService]
    }]
})

使用Injector,只需将其传递给构造函数,然后在

中定义它
import {Injector} from '@angular/core'; 

this.router = this.injector.get(Router);

但不要在构造函数

中执行此操作