在 config() 模块中注入依赖项 - AngularJS

2024-05-22

目前在 app.js 中我有以下路线:

var gm = angular.module('gm', ['gm.services','gm.directives','gm.filters','gm.controllers','ngSanitize']);

gm.config(['$routeProvider', 'Path', function($routeProvider, Path) {

    $routeProvider.when('/login', { 
        templateUrl: Path.view('application/authentication/login.html'), 
        controller: 'authController' 
    });

    $routeProvider.when('/dashboard', { 
        templateUrl: Path.view('application/dashboard/index.html'), 
        controller: 'dashboardController' 
    }); 

    $routeProvider.otherwise({ 
        redirectTo: '/login'
    });

}]);

如您所见,我正在尝试注入路径依赖项。尽管我收到一条错误消息,说找不到该提供商。我认为这是因为配置模块提供程序先于其他任何事情执行。下面是我在“services.js”中的路径提供程序定义

gm.factory("Path", function() {
  return {
    view: function(path) {
      return 'app/views/' + path; 
    },
    css: function(path) {
      return 'app/views/' + path; 
    },
    font: function(path) {
      return 'app/views/' + path; 
    },
    img: function(path) {
      return 'app/views/' + path; 
    },
    js: function(path) {
      return 'app/views/' + path; 
    },
    vendor: function(path) {
      return 'app/views/' + path; 
    },
    base: function(path) {
      return '/' + path; 
    }
  }
}); 

我如何将此提供程序注入到配置模块中?


  1. angular.config只接受提供商
  2. 每个服务、工厂等都是 Provider 的实例

因此,要在配置中注入服务,您只需通过在其名称中添加“Provider”来调用该服务的提供者即可。

angular.module('myApp')
  .service('FooService', function(){
    //...etc
  })
  .config(function(FooServiceProvider){
    //...etc
  });

根据 angularjs 提供者文档 https://docs.angularjs.org/guide/providers

...如果您定义一个工厂配方,则为一个空的提供者类型$get设置为工厂函数的方法会在后台自动创建。

因此,如果您有工厂(或服务),例如:

.factory('myConfig', function(){
  return {
    hello: function(msg){
      console.log('hello ' + msg)
    }
  }
})

您首先需要使用以下命令调用您的工厂$get访问返回对象之前的方法:

.config(function(myConfigProvider){
   myConfigProvider
     .$get()
     .hello('world');
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 config() 模块中注入依赖项 - AngularJS 的相关文章

随机推荐