Home  >  Q&A  >  body text

angular.js - Angular如何创建类似$http的全局service?

(function(angular){
    "use strict";
    angular.module('testModule',function(){
        return {
            test : function(){
                console.info('testModule is ready!');
            }
        }
    });
})(window.angular);
var mainApp = angular.module('mainApp',[]);
mainApp.controller('homeController',['testModule',function(testModule){
  testModule.test();
}]);
"Error: [$injector:unpr] Unknown provider: testModuleProvider
某草草某草草2738 days ago599

reply all(2)I'll reply

  • 迷茫

    迷茫2017-05-15 17:15:05

    Thank you, what you wrote is only 30% correct. Two topics are involved here:

    1. Different modules

    angular.module('testModule')angular.module('mainApp',[]) 是两个不同的module,你想要在 mainApp 中使用 testModule,那么你需要在 angular.module('mainApp', [ 'testModule' ]) Import this dependency.

    2. The global tool class is written incorrectly

    Someone answered it above:

    (function(angular){
        "use strict";
        angular.module('testModule', []).factory('alertService', function() {
            return {
                test : function(){
                    console.info('testModule is ready!');
                }
            }
        });
    })(window.angular);

    When in use, you can:

    var mainApp = angular.module('mainApp',[ 'testModule' ]);
    mainApp.controller('homeController',['alertService',function(alertService){
      alertService.test();
    }]);

    The above code has not been verified and there should be no structural problems. Please debug and solve it by yourself.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-15 17:15:05

    Just define your service as a module, for example:

      var appServices = angular.module('myApp.services', []);
        appServices.factory('alertService', function($rootScope) {
            var alertService = {};
            return alertService;
        });

    reply
    0
  • Cancelreply