AngularJs: 为服务使用别名

AngularJs: using alias for a service

我正在使用 angular 创建一个 reusable library。这个库基本上与使用这个库的用户提供的 service 相关联,并基于它做一些工作。

例如:我们的库中定义了一个名为Login的服务,其中传递了一个User服务,我们检查用户是否是是否登录。

.factory('Login', ['User',
    function(User) {
        return {
            checkLogin: function() {
                //PAGE NOT FOUND ERROR..
                if (User.authenticated) {
                    return true;
                }
                else{
                    return false;
                }
            }
        }; //Return
    }
])

我传递的User服务名称不固定可以有不同的名称像EmployeeCustomer它取决于用户因为这个服务是由用户定义的谁下载了这个库,但无论服务名称如何,都将具有相同的功能。

因此,我需要一些方法将给定的正式服务名称参数映射到用户提供的实际服务名称参数。

例如:一些用户下载了这个库,他定义了User服务,名称为Employee然后我的正式服务名称参数User 通过某些映射函数将映射映射到所提供的实际服务名称。

function map(){
   // maps Employee service ==> User service
   /*
      I want this  map  function  to be something this we use in case of a variable like.
      var x = function(){return 1;}
      var y;
      y = x;
      Now y contains the instance of x
      Is something like this possible in case of services? Since services are passed as dependency injection at runtime.

} 

看来你只需要动态注入,这是可能的:

    app.factory('Login', ['$injector', function($injector) {
        var service;
        function initService(name) {
            service = $injector.get(name);
        }
    ...

然后你像往常一样在服务中使用它。