javascript - 如何包装 $http 服务并在 Controller 中使用它获取的数据?

标签 javascript angularjs http

我想要做的是包装 $http 调用,这样我就可以在应用程序中的任何地方将它用作函数,而无需直接使用它。另外,根据我从服务器收到的内容,我想显示一条消息或其他一般内容并分离逻辑。我的问题是我无法访问服务器发送的数据。我做错了什么?

这是我将 $http 封装在其中的服务:

Application.service('test', ['$http', function ($http)
{
    this.test = function()
    {
        console.log('testttt');
    }

    this.fetchData = function(url, successCallback, errorCallback, parameters)
    {
        if (parameters)
        {
            $http.get(url, {params: parameters})
                .success(function (data) {
                    successCallback();
                })
                .error(function (data) {
                    errorCallback();
                })
                .finally(function(data){
                    console.log(data);
                });
        }
        else
        {
            $http.get(url)
                .success(successCallback)
                .error(errorCallback)
                .finally(function(data) {
                    console.log('finally');
                    console.log(data);
                    if (data.message)
                        console.log(message);
                });
        }

    }
}])

以及我称之为的 Controller :

Application.controller('AccessLoggingController', ['$scope', '$http', 'initData', 'test', function($scope, $http, initData,test)
{
    test.fetchData('/jewelry-room/move-user.action', function(){}, function(){}, {user:2000, task:7});
... etc more code

最佳答案

您实际上并不需要传递成功和错误回调,因为 $http.get 返回一个 promise 。来自 $http文档:

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

为了理解deferred和promise please see this SO question .

fetchData 函数可能如下所示:

this.fetchData = function(url, parameters) {
    return $http.get(url, {params: parameters}).then(
        function(response) {
            // do something 
            return response; // resolves a promise 
        }, 
        function(response) {
            // do something
            return $q.reject("Unable to fetch!"); // rejects a promise  
        });
}

然后您可以在 Controller 中使用服务:

test.fetchData('/jewelry-room/move-user.action', {user:2000, task:7}).then(
    function(result) {
        // success callback
        $scope.action = result;    
    }, 
    function(result) {
        // error callback
        $window.alert(result); // alerts "Unable to fetch!"
    });

或者,如果您出于某种原因仍想传递回调:

this.fetchData = function(url, successCallback, errorCallback, parameters) {
    return $http.get(url, {params: parameters}).then(successCallback, errorCallback);
}

关于javascript - 如何包装 $http 服务并在 Controller 中使用它获取的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223969/

相关文章:

javascript - 如何使用链接的侧边栏来更改网页中的图像?

javascript - 检查字段是否为必填项?

javascript - div 创建后的 $anchorScroll

javascript - 如何在点击时删除父元素? - Angular JS

http - .htaccess 强制 https 但只有一个页面带有 http 或 https

javascript - $http Angular 传递对象?

javascript - 在 JavaScript 中向电话号码添加破折号的正则表达式

javascript - 将变量从 javascript 输出到 HTML 成本表中

mongodb - 使用 angular、express 和 mongodb 的 gridfs 上传文件

Java阅读POST,奇怪的十六进制解释