在AngularJS中使用服务来连接API端点

Using service to interface API endpoints in AngularJS

本文关键字:连接 API 端点 服务 AngularJS      更新时间:2023-09-26

为了在大规模应用程序中分离代码,我实现了一个有角度的样板。鉴于我对Angular的经验不如我对其他Javascript框架的经验丰富,我希望对这个方法有一些输入。

当使用端点时,事情会变得非常混乱,代码开始在AngularJs中重复ESP。在别人的项目上工作,我厌倦了看到…

$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;
    }
}

restthttpcomponent的用法

restHttpComponent.request(postModel.endPoint('getPosts', {
   dateFrom: currentDate
}));

有人能看到这样做的负面影响吗?

尝试将api端点替换为

"https://demo0079948.mockable.io/posts/{id}"