【问题标题】:Conditional injection of a service in AngularJSAngularJS中服务的条件注入
【发布时间】:2015-02-27 13:36:51
【问题描述】:

我已经定义了这样的服务:

angular.module('myApp').service('myService', [
'$rootScope',
...
...

我希望只为新用户实例化我的服务(即当 user.createdAt > 今天)。

如果用户是老用户,有没有办法有条件地注入我的服务或至少销毁我的服务而不会产生任何副作用。

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    如果需要,您可以使用$injector 服务动态获取可注入对象:

    app.controller('DemoCtrl', function($injector) {
      this.clicky = function() {
        myFact = $injector.get('myFactory');
        myFact();
      };
    });
    
    app.factory('myFactory', function() {
      return function() {
        alert('foobar!');
      };
    });
    

    这是一个完整的运行演示:http://jsbin.com/bemakemaja/1/edit

    还有$injector 文档:https://docs.angularjs.org/api/auto/service/$injector

    虽然我建议您不要将服务设计成简单地注入它们会产生副作用,但作为一般准则。

    【讨论】:

      【解决方案2】:

      使用factory而不是service,这样你的服务中就可以有一些检查逻辑

      angular.module('myApp').factory('myService', function () {
      
          if (newUser) {
              return { // your service implementation here
              }
          }
          return undefined;
      };
      

      【讨论】:

        【解决方案3】:

        如果用户是老用户,有没有办法有条件地注入我的服务或至少销毁我的服务而不会产生任何副作用。

        最好在服务内部捕获这个逻辑:

        class Service{
            static $inject = ['$rootScope'];
            constructor($rootScope){
                if (user.createdAt > today){ /*something*/ }
                else {/*other thing*/}
            }
        }
        

        注意:服务是单例,所以条件注入看起来不是一个理想的解决方案。 还可以了解 $inject :https://www.youtube.com/watch?v=Yis8m3BdnEM

        【讨论】:

          猜你喜欢
          • 2017-01-07
          • 2016-11-02
          • 2013-03-02
          • 1970-01-01
          • 2016-12-09
          • 1970-01-01
          • 2013-08-30
          • 2013-04-07
          相关资源
          最近更新 更多