简体   繁体   English

使用服务通过AngularJs中的$ http获取数据

[英]Using a service to get data via $http get in AngularJs

I'm trying to pass data back to my controller from my service with no success. 我试图将数据从服务传递回我的控制器,但没有成功。 I am able to invoke my service from my controller, and I know the service itself works because I can console log the response from within the service (but not back in the controller). 我能够从控制器调用我的服务,并且我知道服务本身可以工作,因为我可以从服务内部(但不能在控制器内部)控制台记录响应。

This is my service: 这是我的服务:

(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;
            });
    };
}
}());

This is inside my controller: 这是在我的控制器内部:

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

I've tried passing the data back as a callback in testService.getData but with no success. 我尝试将数据作为回调传递回testService.getData中,但没有成功。 I have also tried using a factory instead of a service but I'm not able to access the data back in my controller. 我也尝试使用工厂而不是服务,但无法访问控制器中的数据。 I have also tried defining my function in the service differently (getData: function()...) and so on. 我也尝试过以不同的方式在服务中定义我的函数(getData:function()...),依此类推。

I'm guessing my return statement in the service is behaving differently than the way I am expecting. 我猜我在服务中的return语句的行为方式与我期望的方式不同。 I would appreciate any help! 我将不胜感激任何帮助!

getData never returns. getData永不返回。 add return in front of $http and use .then in your controller. 在$ http前面添加return,然后在控制器中使用.then。

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

In ctrl 在Ctrl中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM