如何从角度来获取服务的数据结果

时间:2015-02-28 16:38:42

标签: angularjs http angular-promise

我必须得到来自API的数据,在这种情况下我使用了控制器和服务,它的服务是“daryo.factory”(' daryoSvc',[' $ http',功能($ http){

var categories = [];

var categoriesjon = function () {
    $http.get('http://localhost:18737/Category/GetCategories').
        success(function (data, status, headers, config) {
            categories = {
                "one": "two",
                "key": "value"
            };
            alert('g');
        })
        .error(function (data, status, headers, config) {
            console.error(data);
        });

    return categories;
}

var factoryService = {
    categories: categoriesjon
};

return factoryService;

}]);`

这是我的Controller函数`daryo.controller(' daryoCtrl',[' $ scope',' daryoSvc',function($ scope,daryoSvc)) {

var self = $scope;
self.categories = daryoSvc.categories;

console.log(daryoSvc.categories);

}]);`

它无法正常工作,因为我没有使用$ q承诺选项而且我没有找到一个很好的解决方案,我该如何解决?谢谢!

1 个答案:

答案 0 :(得分:2)

您的服务返回一个空数组。一旦异步http调用成功,则该空数组将被新的替换,但使用此服务的控制器仍然具有对旧的空数组的引用。另一个问题是控制器甚至不调用该服务。它所做的就是在范围内存储对服务功能的引用。

代码应为

var categoriesjon = function () {
    // executed at t1
    return $http.get('http://localhost:18737/Category/GetCategories').
        then(function (response) {
            // executed at t2, long after t1
            var categories = {
                "one": "two",
                "key": "value"
            };
            return categories;
        })
        .catch(function (response) {
            console.error(response.data);
        });
};

并在控制器中:

// executed at t0
daryoSvc.categories().then(function(data) {
    // executed at t3
    $scope.categories = data;
});