0

在 Angular 2 自定义 http 服务的文章之后它还利用另一个自定义 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 服务中注入 Router 服务时,会出现一些注入错误。

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

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

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 服务中注入 Router 服务,以便可以使用客户端导航?

我在这里创建了一个 plnkr 也显示了错误。

4

1 回答 1

2

此代码是原因:

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

“在注入路由器之前引导至少一个组件”

工厂实例化HttpErrorHandlerRouter作为它之前的依赖AppComponent

于 2016-04-18T22:25:08.467 回答