【问题标题】:AngularJs Service return empty list [duplicate]AngularJs服务返回空列表[重复]
【发布时间】:2019-09-17 16:30:33
【问题描述】:

我需要通过我的 angularjs 服务发出一个 http 请求。我知道它是异步工​​作的,但我无法捕获我的数据。

var dataRifValues = [];

monitoraggioProcessiService.getDataRifList().then(function(response) {
    angular.forEach(response, function(date, key) {
        dataRifValues.push(date.dataRiferimento);
    });
});

this.getDataRifList = function() {
    var url = $rootScope.baseLink + "/processi/dataRif";
    var deferred = $q.defer();
    var list = [];
    if (list.length === 0) {
        var promise = ispCommunicationManager.returnPromise(
                          ispServiceRequest.prepareRequest(url,"GET",
                                {
                                    "Content-Type" : "application/json"
                                }, null, null));
        promise.then(function(response) { // Success callback
            list = response.data;
            deferred.resolve(response.data); // Resolve
        }, function(response) { // Error callback
            list = response;
            deferred.reject(response); // Reject
            util.defaultErrorHandler(list,null);
        });
        list = deferred.promise;
    }
    return list
 }

我正在调用 getDataRifList 函数。我希望有一个包含一些数据的列表。

这就像它被调用了两次。第一次列表为空,第二次有数据,但是我的函数已经执行了。

什么是错误?

编辑

调用有效,但是当我需要设置 filtroDataRiferimento 选定属性时,dataRifValues[0] 为空。相反,values 属性具有值。

var filtroDataRiferimento = {

                label : "Data di riferimento",
                name : "dataRiferimento",
                type : "single",
                values : dataRifValues,
                selected : dataRifValues[0],
                flagMatch : false

            };

        $scope.filtraMonitoraggioProcessi(filtroDataRiferimento.selected);

【问题讨论】:

    标签: javascript angularjs promise httprequest


    【解决方案1】:

    getDataRifList 函数正在执行多个活动。我相信但不确定只是返回承诺对象也应该解决问题,而不是创建和返回延迟对象。 而util.defaultErrorHandler(list,null);可以在getDataRifList()调用失败的情况下处理。

    提示:不需要检查长度,因为变量的声明刚好在条件if (list.length === 0) {

    之上

    【讨论】:

    • 您好,感谢您的帮助。我尝试使用简单的 $http 请求,但我遇到了同样的问题。调用有效,但值仍然为空。我编辑我的问题:)
    猜你喜欢
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2017-10-27
    • 2018-06-25
    相关资源
    最近更新 更多