通用、惯用且可维护的方法是将数据访问逻辑封装到专用的 AngularJS 服务中。该服务本身将使用内置在 HTTP 客户端服务中的框架,该框架已针对 JSON 友好的默认行为进行了优化。
为了利用前面提到的 AngularJS HTTP 客户端服务,我们实际上将创建一个可注入服务工厂,它将接收 HTTP 客户端作为参数并返回我们的服务。服务本身只是一个简单的对象,它公开了一个从 API 端点获取用户的函数。
这是我们的服务工厂的样子
(function () {
userService.$inject = ['$http']; // tell AngularJS to inject HTTP service as first param
function userService($http) {
var apiUrl = 'http://54.87.197.206:8080/SparkServer/admin/api/v1/listOf/users';
var service = {
getUsers: function() {
return $http.get(apiUrl)
.then(function (response) {
return response.data;
});
},
createUser: function(user) {
return $http.post(apiUrl, user)
.then(function (response) {
return response.data;
});
}
};
return service;
}
现在我们已经创建了服务工厂并使用$inject 属性告诉AngularJS 注入它的$http 服务,我们只需要注册它。
angular.module('app') // assumes module is already defined by other code
.factory('userService', userService);
}());
现在我们可以将userService 注入到控制器、指令或其他服务中。
比如我们可能有一个UsersController需要访问服务(工厂返回的对象)。
这就是这样一个控制器的样子
(function () {
UsersController.$inject = ['userService']; // inject the service we registered above
function UsersController(userService) {
var that = this;
this.users = []; // initialize to empty array while we wait for data to load
userService.getUsers()
.then(function (users) {
that.users = users;
})
.catch(function (error) {
console.error(error);
});
this.newUser = {};
this.createUser = function (user) {
return userService.createUser(that.newUser)
.then(function (user) {
that.users.push(user);
that.newUser = {};
})
.catch(function (error) {
console.error(error);
});
};
}
}());
create-user.html
<form ng-submit="$ctrl.createUser()">
name:
<input type="text" ng-model="$ctrl.newUser.name" name="name" />
password:
<input type="password" ng-model="$ctrl.newUser.password" name="password" />
confirm password:
<input type="password" ng-model="$ctrl.newUser.confirmPassword" name="confirm-password" />
<input type="submit" id="submit" value="Submit" />
</form>
create-user.js
(function () {
var createUser = {
templateUrl: './create-user.html',
controller: 'UsersController'
};
angular.module('app')
.component('createUser', createUser);
}());