javascript - 如何使用 $http 为 Rest API 调用创建通用服务?

标签 javascript jquery angularjs

我想要从我的 Controller 调用的通用服务。我希望动态传递选项。

例如。

var app = angular.module('common', []);

app.factroy('APIService', ['$http', function($http){

    return {

        doApiCall: function(url, method, payload, headers){

        // I should make a call to server with the parameters passed from the controller.
        //

        }

    }

}]);


app.controller('SampleCtrl', ['$scope', 'common' , function($scope, common){

    // I want to call the doApiCall function provided by common service based the application requirements.

    common.doApiCall('api/user', 'GET', function(){

    });

    common.doApiCall('api/user', 'POST', function(){

    });

    common.doApiCall('api/user', 'DELETE', function(){

    });

    common.doApiCall('api/user', 'PUT', function(){

    });

});

我想要像上面这样的东西,但我做不到?谁能告诉我如何制作用于访问 REST API 服务的通用函数。提前致谢。

最佳答案

我在您的代码中看到两个错误:

1) 将 app.factroy 替换为 app.factory

2)在您的 Controller 中,您注入(inject)您的应用程序模块而不是您的服务,请参阅:

app.factory('APIService', ['$http', function($http) {

    return {
        doApiCall: function(url, method, payload, headers){

            // I should make a call to server with the parameters passed
            // from the controller.

            var xhr = $http({
                method: method,
                url: url,
                headers: headers || {}, // Optional headers
            });

            // You probably want to differentiate success / error handlers
            xhr.success(payload);
            xhr.error(payload);

            return xhr;
        }
    };
}]);

app.controller('SampleCtrl', ['$scope', 'APIService' , function($scope, api) {

    // You should be able to call your service:
    api.doApiCall('api/user', 'DELETE', function(data) {
        console.log(data);
    });
});

关于javascript - 如何使用 $http 为 Rest API 调用创建通用服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839451/

相关文章:

Javascript 从 compose 函数中减少

javascript - 如何将 css 类添加到一组链接中的特定链接?

jquery - 修改 bootstrap Popover Html 内容不持久

javascript - 如何通过表单外的元素在移动设备上提交表单

javascript - getBoundingClientRect() 返回错误的宽度

javascript - Angular 绑定(bind)字符串日期到输入类型日期

javascript - JS倒计时代码

javascript - 流重定向后确定 JavaScript 中 <audio> 标记的来源

javascript - jQuery 后代选择器和多重选择器

javascript - Angular Material 的 md-autocomplete 中的跳跃文本