在这里,您可以直接从文档中获取:
Registering a Service with $provide
You can also register services via the $provide service inside of a module 's config function:
angular
.module('myModule', [])
.config(['$provide ',
function($provide) {
$provide.factory('serviceId ', function() {
var shinyNewServiceInstance;
// factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
}
]);
This technique is often used in unit tests to mock out a service'
s dependencies.
希望这可以帮助。
(function() {
'use strict';
angular
.module('example.app', [])
.config(['$provide',
function($provide) {
$provide.factory('serviceId', function() {
var shinyNewServiceInstance;
// factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
}
])
.controller('ExampleController', ExampleController)
.service('exampleService', exampleService);
exampleService.$inject = ['$http'];
function ExampleController(exampleService) {
var vm = this;
vm.update = function(person, index) {
exampleService.updatePeople(person).then(function(response) {
vm.persons = response;
}, function(reason) {
console.log(reason);
});
};
}
// good practice to use uppercase variable for URL, to denote constant.
//this part should be done in a service
function exampleService($http) {
var URL = 'https://beta.test.com/auth/authenticate/',
data = {},
service = {
updatePeople: updatePeople
};
return service;
function updatePeople(person) {
//person would be update of person.
return $http
.post(URL, person)
.then(function(response) {
return response.data;
}, function(response) {
return response;
});
}
}
})();