错误:未知提供程序/正在访问工厂中的控制器



如何访问以下代码中的AuthenticationCtrl?

代码:

app.factory( 'AuthenticationInterceptor', function( $q, $injector ) 
{
    return {
        response: function (response) 
        {
            // Bypass the success.
            return response;
        },
        responseError: function (response) 
        {   
            // Sign out if the user is no longer authorized.
            if (response.status == 401) 
            {
                console.log("test 1"); // shows up in console
                var AuthenticationCtrl = $injector.get( 'AuthenticationCtrl' );
                console.log("test 2"); // does not show up in console
                AuthenticationCtrl.signOut();
            }
            return $q.reject(response);
        }
    };
});

错误:

Error: Unknown provider: AuthenticationCtrlProvider <- AuthenticationCtrl
at Error (native)
at file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:2765:46
at Object.getService [as get] (file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:2891:39)
at file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:2770:45
at Object.getService [as get] (file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:2891:39)
at responseError (file:///C:/node/corsnection/client/app/scripts/common/interceptor/AuthenticationInterceptor.js:17:40)
at wrappedErrback (file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:7518:57)
at wrappedErrback (file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:7518:57)
at file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:7630:53
at Object.Scope.$eval (file:///C:/node/corsnection/client/app/components/angular-unstable/angular.js:8926:28) 

PS:代码来自https://github.com/pablodenadai/Corsnection-我正在努力让它为我工作,以了解有关节点和角度的用户身份验证。

$injector.get()只能用于获取服务和服务。控制器是通过$ControllerProvider实例化的,因为它们需要特殊处理。他们需要一个范围,例如

此外,控制器不是单态,因此不会得到AuthenticationCtrl,而是一个AuthenticationCtrl

即使你得到了控制器(这是可能的),在你的情况下也是完全无用的,因为AuthenticationCtrl没有方法(在github的代码中)。这意味着您不能调用AuthenticationCtrl.signOut(),因为signOut()是在视图的范围中定义的。

正如其他人所指出的,您可以使用服务来完成此任务。或者您触发控制器侦听的事件。

最新更新