在angularJS中将服务注入另一个服务

 Triste夏木_668_365 发布于 2023-02-05 09:31

是否可以在angularJS中将一项服务注入另一项服务?

3 个回答
  • 是.像这样(这是一个提供者,但同样适用)

        module.provider('SomeService', function () {
    
    
        this.$get = ['$q','$db','$rootScope', '$timeout', 
                    function($q,$db,$rootScope, $timeout) {
              return reval;
        }
        });
    

    在此示例中,$db是在应用程序的其他位置声明并注入提供程序$get函数的服务.

    2023-02-05 09:35 回答
  • 为了避免混淆,我认为值得一提的是,如果您在childService中使用任何其他服务(例如$ http,$ cookies,$ state),那么您还需要明确声明它们.

    例如

    function() {
      var childService = function($http, $cookies, parentService) {
    
      // Methods inherited
      this.method1Inherited = parentService.method1();
      this.method2Inherited = parentService.method2();
    
      // You can always add more functionality to your child service
    
      angular.module("app").service("childService", ["$http", "$cookies", "parentService", childService]);
    
    }());
    

    您可以在数组中声明您在子项内使用的服务,然后自动注入它们,或者使用$ inject注释单独注入它们:

    childService.$inject = ["$http", "$cookies", "parentService"]; 
    angular.module("app").service("childService ", childService );
    

    2023-02-05 09:35 回答
  • 是.遵循angularjs中的常规注射规则.

    app.service('service1', function(){});
    
    //Inject service1 into service2
    app.service('service2',function(service1){});
    

    感谢@simon.最好使用Array注入来避免缩小问题.

      app.service('service2',['service1', function(service1) {}]);
    

    2023-02-05 09:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有