在注射服务的app.config [英] Inject service in app.config
问题描述
欲注入一个服务成的app.config,以便可在控制器被调用之前被检索的数据。我想这样的:
I want to inject a service into app.config, so that data can be retrieved before the controller is called. I tried it like this:
服务:
app.service('dbService', function() {
return {
getData: function($q, $http) {
var defer = $q.defer();
$http.get('db.php/score/getData').success(function(data) {
defer.resolve(data);
});
return defer.promise;
}
};
});
配置:
app.config(function ($routeProvider, dbService) {
$routeProvider
.when('/',
{
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
data: dbService.getData(),
}
})
});
但我得到这个错误:
But I get this error:
错误:未知提供商:从EditorApp dbService
Error: Unknown provider: dbService from EditorApp
如何正确的设置,并注入这项服务?
How to correct setup and inject this service?
推荐答案
亚历克斯规定不能够做你想要做什么,所以+1正确的原因。但你是因为你没有使用相当结算时他们是如何设计遇到此问题。
Alex provided the correct reason for not being able to do what you're trying to do, so +1. But you are encountering this issue because you're not quite using resolves how they're designed.
决心
它可以是一个服务或返回值的函数的字符串被注入。既然你做了后者,你需要在实际的功能来传递:
resolve
takes either the string of a service or a function returning a value to be injected. Since you're doing the latter, you need to pass in an actual function:
resolve: {
data: function (dbService) {
return dbService.getData();
}
}
在框架去解决数据
,它会注入 dbService
进入功能,使您可以自由使用它。你并不需要注入配置
块都做到这一点。
When the framework goes to resolve data
, it will inject the dbService
into the function so you can freely use it. You don't need to inject into the config
block at all to accomplish this.
个饱!
这篇关于在注射服务的app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!