在bootstrap阶段期间Angular 2自定义http错误处理程序服务注入问题

时间:2016-04-18 22:07:29

标签: angular angular2-routing angular2-services angular2-http

关于Angular 2自定义http服务here的文章:它还利用另一个自定义http错误服务来处理http错误代码并重新加载屏幕,此服务的代码位于:

@Injectable()
export class HttpErrorHandler {

    constructor(
        private apiGateway: ApiGateway
    ) {
        apiGateway.errors$.subscribe(
            (value: any) => {
                console.group("HttpErrorHandler");
                console.log(value.status, "status code detected.");
                console.dir(value);
                console.groupEnd();
                // If the user made a request that they were not authorized
                // to, it's possible that their session has expired. Let's
                // refresh the page and let the server-side routing move the
                // user to a more appropriate landing page.
                if (value.status === 401) {
                    window.location.reload();
                }
            });
    }
}

我想要实现的是401错误重定向到登录路由使用:

router.navigate(['Login']);

但是,当我在HttpErrorHandler服务中注入路由器服务时,我会收到一些注入错误。

Error: EXCEPTION: Error during instantiation of Token RouterPrimaryComponent! (Token Application Initializer -> HttpErrorHandler -> Router -> RouteRegistry -> Token RouterPrimaryComponent)

注意:上面的HttpErrorHandler是在应用程序的bootstrap阶段配置的,如下所示:

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    ApiGateway,
    FriendService,
    HttpErrorHandler,
    //
    // Make sure our "unused" services are created via the
    //  APP_INITIALIZER token
    //
    provide(APP_INITIALIZER, {
        useFactory: (httpErrorHandler) => {
            console.info( "HttpErrorHandler initialized." );
        },
        deps: [HttpErrorHandler]
    })
]);

我不确定我是否在应用程序生命周期的早期注入路由器服务。有没有办法在HttpErrorHandler服务中注入路由器服务,以便可以使用客户端导航?

我创建了一个plnkr here来显示错误。

1 个答案:

答案 0 :(得分:2)

此代码是原因:

provide(APP_INITIALIZER, {
    useFactory: (httpErrorHandler) => {
        console.info( "HttpErrorHandler initialized." );
    },
    deps: [HttpErrorHandler]
})
  

"在注入Router"

之前引导至少一个组件

工厂在HttpErrorHandler之前实例化RouterAppComponent作为其依赖关系。