Javascript 在AngularJS中使用服务接口API端点
在大规模应用程序中分离代码的过程中,我实现了一个角度样板。从目前来看,我在Angular方面的经验不如在其他Javascript框架方面的经验,我希望对这种方法有所了解 当使用端点时,事情会变得非常混乱,代码开始重复,尤其是使用AngularJs时。在别人的项目上工作我讨厌看到Javascript 在AngularJS中使用服务接口API端点,javascript,jquery,angularjs,api,frontend,Javascript,Jquery,Angularjs,Api,Frontend,在大规模应用程序中分离代码的过程中,我实现了一个角度样板。从目前来看,我在Angular方面的经验不如在其他Javascript框架方面的经验,我希望对这种方法有所了解 当使用端点时,事情会变得非常混乱,代码开始重复,尤其是使用AngularJs时。在别人的项目上工作我讨厌看到 $http({ method: 'GET', url: '/posts' }).then(function successCallback(response) { // code }, function
$http({
method: 'GET',
url: '/posts'
}).then(function successCallback(response) {
// code
}, function errorCallback(response) {
// code
});
因此,我构建了一个组件,该组件基本上与http组件接口,但应用了我们现有的restful标准(正确处理http状态)、作用域、本地存储等,并结合了一种为端点接口实现服务的方法,该方法严格描述端点以及它们如何与应用程序相适应
angular.module('Ripple').service('postModel', [function() {
'use strict';
return {
/**
* Rest Endpoint interface
* @type {Object}
*/
_rest: {
getPosts: {
url: 'http://localhost:3000/posts',
method: 'GET',
scopeUpdate: 'posts',
localStorage: false,
params: {
// Endpoint params
}
},
getPost: {
url: 'http://jsonplaceholder.typicode.com/posts/',
method: 'GET',
scopeUpdate: 'post',
localStorage: false,
pagination: false,
params: {
id: 1
}
},
getError: {
url: 'https://demo0079948.mockable.io/posts',
method: 'GET',
scopeUpdate: 'post',
localStorage: false,
pagination: false,
params: {
// none
}
},
},
/**
* Returns rest objects and allows to extend the params property
* @param {string} method
* @param {object} options
* @return {object}
*/
endPoint: function(endPointMethod, options) {
var defaults = this._rest[endPointMethod];
$.extend(defaults.params, options);
return defaults;
}
}
使用restHttpComponent
restHttpComponent.request(postModel.endPoint('getPosts', {
dateFrom: currentDate
}));
任何人都能看到这样做的负面影响吗?只要尝试将api端点替换为
“{id}”我不会为您检查代码,但原则上,这是可行的。我也做同样的事情,但我将我的方法链接起来,以便能够调用更深层次的端点,例如
service.one('topic',1)。one('subject',33)。get('comment',3)
。仅供参考,还有一个Restangular可以做同样的事情,而且很容易使用。看起来不错,谢谢你的反馈