javascript - 在 AngularJs 中使用服务通过 $http get 获取数据

标签 javascript angularjs

我正在尝试将数据从我的服务传递回我的 Controller ,但没有成功。我能够从 Controller 调用我的服务,并且我知道服务本身可以工作,因为我可以控制台记录服务内的响应(但不能返回 Controller )。

这是我的服务:

(function () {
angular
    .module('app')
    .service('testService', testService);

testService.$inject = ['$http'];

function testService($http, url) {
    var baseUrl = "http://getjsondata.com/" + url;

    this.getData = function (url) {
        $http({
            method: 'GET',
            url: baseUrl + url,
            headers: {'Content-Type': 'application/json'}
        })
            .then(function (response) {
                console.log(response); // THIS WORKS
                return response;
            })
            .catch(function (error) {
                return error;
            });
    };
}
}());

这是在我的 Controller 内:

vm.getTestData = function (url) {
    vm.response = testService.getData(url);
    console.log(vm.response);
};

我尝试将数据作为 testService.getData 中的回调传递回来,但没有成功。我还尝试使用工厂而不是服务,但我无法访问 Controller 中的数据。我还尝试以不同的方式在服务中定义我的函数(getData:function()...)等等。

我猜我在服务中的返回语句的行为与我预期的不同。我将不胜感激任何帮助!

最佳答案

getData 永远不会返回。在 $http 前面添加 return 并在 Controller 中使用 .then 。

this.getData = function (url) {
    return $http({
        method: 'GET',
        url: baseUrl + url,
        headers: {'Content-Type': 'application/json'}
    })
};

按ctrl键

vm.getTestData = function (url) {
    testService.getData(url).then(function (response) {
        vm.response = response; 
        return response;
    })
    .catch(function (error) {
        return error;
    });
};

关于javascript - 在 AngularJs 中使用服务通过 $http get 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48608430/

相关文章:

javascript - 行编辑插件: disable editing and actioncolumn delete icon

javascript - 从服务器获得响应后关闭 Controller 中的 Bootstrap 模式

javascript - 下拉菜单依赖于 AngularJS 中的另一个下拉菜单

javascript - 将 HTML 表导出到 Excel 不使用 C# 下载文件

AngularJS - 取消观察大括号内的自动绑定(bind)值

javascript - 如何: React serialise multidimensional array and unserialise it in PHP

javascript - 绘制 Three.js BufferGeometry 线时,颜色不会粘在线段上

javascript - 使用 AngularJS 打造原生桌面/移动应用程序?

javascript - 我怎么知道 Axis 上显示的是什么日期?

javascript - 如何在带有文本的 Html 框中创建建议框(Javascript 中的提示框)