簡體   English   中英

使用服務通過AngularJs中的$ http獲取數據

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

我試圖將數據從服務傳遞回我的控制器,但沒有成功。 我能夠從控制器調用我的服務,並且我知道服務本身可以工作,因為我可以從服務內部(但不能在控制器內部)控制台記錄響應。

這是我的服務:

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

這是在我的控制器內部:

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

我嘗試將數據作為回調傳遞回testService.getData中,但沒有成功。 我也嘗試使用工廠而不是服務,但無法訪問控制器中的數據。 我也嘗試過以不同的方式在服務中定義我的函數(getData:function()...),依此類推。

我猜我在服務中的return語句的行為方式與我期望的方式不同。 我將不勝感激任何幫助!

getData永不返回。 在$ http前面添加return,然后在控制器中使用.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;
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM