Angularjs Can';t将本机angular服务注入自定义提供程序

Angularjs Can';t将本机angular服务注入自定义提供程序,angularjs,angularjs-service,angularjs-provider,Angularjs,Angularjs Service,Angularjs Provider,我正在尝试创建一个提供商来处理我的应用程序中的身份验证 function Authenticator($http) { console.log($http); return { test: function() {} } } app.provider('authenticator', function AuthenticatorProvider() { this.config =

我正在尝试创建一个提供商来处理我的应用程序中的身份验证

     function Authenticator($http) {
        console.log($http);
        return {
            test: function() {}
        }
    }

    app.provider('authenticator', function AuthenticatorProvider() {

        this.config = function () {
            var requestParams;
            return {
                setRequestParams: function (params) {
                    requestParams = params;
                }
            }
        }();


        this.$get = function($http) {
            return new Authenticator($http);
        };

    });
当我运行高于$http的代码时,它被设置为未定义。我做错了什么?将$http服务注入自定义提供程序的正确方法是什么


谢谢

我猜你真正想做的事情是这样的:

app.factory('AuthenticationService', ['$http', function($http) {
    var AuthenticationService = function() {};

    AuthenticationService.prototype.config = function)() { ... }

    return new AuthenticationService();
}]);

这将创建一个可以注入到其他控制器、指令和服务中的服务,这些控制器、指令和服务将只有一个共享实例。通过字符串获取服务意味着函数中的引用是闭包的本地引用,这意味着可以安全地重命名变量,节省宝贵的带宽。

我猜您真正想做的是这样的:

app.factory('AuthenticationService', ['$http', function($http) {
    var AuthenticationService = function() {};

    AuthenticationService.prototype.config = function)() { ... }

    return new AuthenticationService();
}]);

这将创建一个可以注入到其他控制器、指令和服务中的服务,这些控制器、指令和服务将只有一个共享实例。通过字符串获取服务意味着函数中的引用是闭包的本地引用,这意味着可以安全地重命名变量,从而节省宝贵的带宽。

我曾经尝试过这样做。。。但我将$http作为参数传递给AuthenticationService。所以我删除了$http,就像你说的那样,它成功了!谢谢工作正常,但我必须调用authenticatorProvider。$get()使其工作,我不知道这是否是一种好的做法。。。是吗?您必须像注入$http一样,在某个地方注入它,才能实例化服务。我没有看到authenticatorProvider或$get()在该小提琴上的任何用法,因此我不完全确定问题出在哪里。看,我已经将app.config函数放在了提供者的正下方。第一个console.log返回
对象{$get:function}
。第二个控制台日志(调用.$get())返回
对象{getUserInfo:function,login:function,logout:function,setRequestParams:function,getRequestParams:function}
Ah。您可以访问app.config()中的提供程序和app.run()中的实例。我不知道angular会在您提供服务时自动为您创建提供商,这很酷。不管怎么说,我猜您应该在app.config中的某个地方使用var authenticator=authenticatorProvider.$get(),然后您就有了一个可以使用的对象。但如果可能的话,我会推迟对你自己创建的服务进行任何操作,直到应用程序运行。我会尝试这样做。。。但我将$http作为参数传递给AuthenticationService。所以我删除了$http,就像你说的那样,它成功了!谢谢工作正常,但我必须调用authenticatorProvider。$get()使其工作,我不知道这是否是一种好的做法。。。是吗?您必须像注入$http一样,在某个地方注入它,才能实例化服务。我没有看到authenticatorProvider或$get()在该小提琴上的任何用法,因此我不完全确定问题出在哪里。看,我已经将app.config函数放在了提供者的正下方。第一个console.log返回
对象{$get:function}
。第二个控制台日志(调用.$get())返回
对象{getUserInfo:function,login:function,logout:function,setRequestParams:function,getRequestParams:function}
Ah。您可以访问app.config()中的提供程序和app.run()中的实例。我不知道angular会在您提供服务时自动为您创建提供商,这很酷。不管怎么说,我猜您应该在app.config中的某个地方使用var authenticator=authenticatorProvider.$get(),然后您就有了一个可以使用的对象。但如果可能的话,我会推迟对您自己创建的服务进行任何操作,直到应用程序运行。