将您的服务设置为自定义AngularJS提供程序
尽管接受的答案说什么,你居然CAN做什么你打算这样做,但你需要将其设置为一个可配置的提供者,因此它在配置阶段是可用的服务。首先,你的改变Service
到提供者如下所示。此处的主要区别在于,在设置了的值之后defer
,您可以将defer.promise
属性设置为返回的Promise对象$http.get
:
提供者服务:(提供者:服务配方)
app.provider('dbService', function dbServiceProvider() {
//the provider recipe for services require you specify a $get function
this.$get= ['dbhost',function dbServiceFactory(dbhost){
// return the factory as a provider
// that is available during the configuration phase
return new DbService(dbhost);
}]
});
function DbService(dbhost){
var status;
this.setUrl = function(url){
dbhost = url;
}
this.getData = function($http) {
return $http.get(dbhost+'db.php/score/getData')
.success(function(data){
// handle any special stuff here, I would suggest the following:
status = 'ok';
status.data = data;
})
.error(function(message){
status = 'error';
status.message = message;
})
.then(function(){
// now we return an object with data or information about error
// for special handling inside your application configuration
return status;
})
}
}
现在,您有了一个可配置的自定义提供程序,只需要注入它即可。此处的主要区别是缺少“可注射的提供者”。
配置:
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
dbData: function(DbService, $http) {
/*
*dbServiceProvider returns a dbService instance to your app whenever
* needed, and this instance is setup internally with a promise,
* so you don't need to worry about $q and all that
*/
return DbService('http://dbhost.com').getData();
}
}
})
});
使用您的已解析数据 appCtrl
app.controller('appCtrl',function(dbData, DbService){
$scope.dbData = dbData;
// You can also create and use another instance of the dbService here...
// to do whatever you programmed it to do, by adding functions inside the
// constructor DbService(), the following assumes you added
// a rmUser(userObj) function in the factory
$scope.removeDbUser = function(user){
DbService.rmUser(user);
}
})
可能的选择
以下替代方法是类似的方法,但是允许在中定义.config
,将服务封装到应用程序上下文中的特定模块中。选择适合您的方法。另请参阅以下第三种替代方法的注释以及有用的链接,以帮助您掌握所有这些内容
app.config(function($routeProvider, $provide) {
$provide.service('dbService',function(){})
//set up your service inside the module's config.
$routeProvider
.when('/', {
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
data:
}
})
});
一些有用的资源
该提供程序为您提供了比该.service
方法更多的配置,这使其更适合作为应用程序级别的提供程序,但是您也可以通过将其注入$provide
config 来将其封装在config对象本身中,如下所示: