Angular在config中注入$ state服务以重定向到拦截器中的状态

时间:2016-08-31 00:12:33

标签: angularjs typescript angular-ui-router restangular inject

我使用的是restangular,我有一个拦截器。这个想法是,对于每个响应401,拦截器应该重定向到不同的状态。

问题是angular不允许在config中注入服务。它只允许注入提供者。

如何才能访问我的restangular拦截器中的$state: ng.ui.IStateService

我知道我可以注入提供商$stateProvider: ng.ui.IStateProvider,但我认为没有办法从提供商导航到某个州。

这就是我所拥有的:

/// <reference path="../../typings/globals/restangular/index.d.ts" />

((): void => {
    "use strict";

    angular
        .module("app")
        .config(configRestangular);

    configRestangular.$inject = [
        "$state",
        "RestangularProvider",
        "authSettings",
        "stateNames",
        "apiUrl"
    ];

    function isCustomValidationErrorResponse(response: restangular.IResponse) {
        return (response.data && response.data.customValidationError === true);
    }

    function configRestangular(
        $state: ng.ui.IStateService,
        restangularProvider: restangular.IProvider,
        authSettings: IAuthSettings,
        stateNames: IStateNames,
        apiUrl: string) {

        // restangular settings
        restangularProvider.setBaseUrl(apiUrl);

        restangularProvider.setErrorInterceptor((response: restangular.IResponse, deferred: ng.IDeferred<any>) => {
            if (response.status === 401) {
                $state.go(stateNames.login); //this will fail because $state cannot be injected here and I don't know how to navigate to a different state from $stateProvider
            } 
            return true;
        });
    }
})();

1 个答案:

答案 0 :(得分:3)

方法是 - 在 .run() 阶段中配置Restangular.setErrorInterceptor(查看Restangular而非RestangularProvider。我们可以按预期获得$state

另见:

Configuring in the run

// Here I inject the service BaseUrlCalculator which I need
app.run(function(Restangular, BaseUrlCalculator) {
    Restangular.setBaseUrl(BaseUrlCalculator.calculate());
});