Angular JS回调没有初始化数据

时间:2016-05-25 22:24:24

标签: angularjs callback angular-services

我遇到了回调和异步请求的问题。我创建了一个服务来获取使用回调的数据(一旦calls_left命中0,就会调用回调)。我在我的控制器中注入我的服务,然后在我的服务(metr.getMInterval)上调用getMInterval,它应该初始化数据(在这种情况下是pTypes)并等到它完成。问题是pTypes首先记录为空Array []。有什么想法吗?

服务:

angular.module('mService', ['config']).service('metr', function($http, $window, $rootScope, $location, config) {

var pTypes = [];
var intervalData = {};


function fetchMInterval(callback) {

    var calls_left = 1;
    var onComplete = function() {
        calls_left--;
        if (calls_left == 0) {
            console.log("finished retrieving data from api");
            if (callback) callback();
        }
    };

    var url = 'fetch_data_from_this_url';
    $http({
        method: 'GET',
        url: url
    }).then(function success(response) {
        console.log(response);
        var data = JSON.parse(response.data.split(config.DELIMITER)[1]);

        intervalData = data["Data"];
        pTypes = metrIntervalData["pTypes"];
        onComplete();

    }, function error(response) {
        alert("Failed to fetch info from " + url + "! " + response.status);
        onComplete();
    });
}

 return {

        getMInterval:function() {return fetchMInterval();},
        getPTypes:function() {return pTypes;},
    }

控制器:

 app.controller('mController', function($scope, $filter, metr, config) {

      metr.getMInterval();

      $scope.pTypes = metr.pTypes();

      console.log(metr.pTypes());   //console logs Array []


  });

0 个答案:

没有答案