我需要做的就是下载一个json文件,并在设置路径后将其分配给PCategory提供程序中的OCategories.但是我收到$http不存在的错误.如何将其注入我的提供程序并下载到setPath函数中?
var app = angular.module('NSApp',[ 'ui.bootstrap','MDItem','MDUser','MDNotification','MDUpload' ] ); app.config(function(PCategoriesProvider) { PCategoriesProvider.setPath('data/csv/categories.json'); });
MDItem /供应商/ category.js
angular.module('MDItem').provider('PCategories',function(){ var OCategories; var OPath; return{ setPath: function(d){ OPath = d; console.log('Path is set. Trying to download categories.'); OCategories = $http.get(oPath); },$get : function() { return { categories : OCategories } } }
});
解决方法
您永远不能将服务实例注入配置函数或提供程序,因为它们尚未配置.存在提供程序以在注入之前配置特定服务.这意味着,某个服务总是有相应的提供商.只是为了澄清,这是使用$locationProvider配置$location服务的一个小例子:
angular.module('myModule').config(function ($locationProvider) { $locationProvider.html5Mode(true); });
那么这里发生的是我们配置$location服务以使用其html5mode.我们通过使用$locationProvider提供的接口来实现这一点.在执行config()时,还没有任何服务实例可用,但您可以在实例化之前配置任何服务.
稍后在运行时(最早的时刻是run()函数),您可以注入一个服务.注入服务时获得的是它的provider $get()方法返回的内容.这也意味着,每个提供者必须有一个$get()函数,否则$injector会抛出一个错误.
但是,在没有构建提供商的情况下创建自定义服务会发生什所以类似于:
angular.module('myModule').factory('myService',function () { ... });
你只是不必关心,因为棱角分明适合你.每次注册任何类型的服务(除非它不是提供者),angular将为您设置一个带有$get()方法的提供者,因此$injector能够稍后实例化.
那么如何解决你的问题.如何在配置短语中使用$http服务进行异步调用?答案:你做不到.
您可以做的是,只要您的服务被实例化,就会运行$http调用.因为在您的服务实例化时,您可以注入其他服务(就像您一直这样).所以你实际上会做这样的事情:
angular.module('myModule').provider('custom',function (otherProvider,otherProvider2) { // some configuration stuff and interfaces for the outside world return { $get: function ($http,injectable2,injectable3) { $http.get(/*...*/); } }; });
现在,您的自定义提供程序返回一个以$http作为依赖项的服务实例.一旦您的服务被注入,它的所有依赖项也会被注入,这意味着在$get中您可以访问$http服务.接下来,您只需拨打电话即可.
为了尽快调用此调用,您必须在run()短语中注入自定义服务,如下所示:
angular.module('myModule').run(function (custom,injectable2) { /* custom gets instantiated,so its $http call gets invoked */ });
希望这能使事情变得清晰.