Angular中的过滤和$http承诺

Filtering and $http promises in Angular

本文关键字:http 承诺 过滤 Angular      更新时间:2023-09-26

我在从JSON文件中过滤数据时遇到了问题,JSON文件是一个由20个对象组成的数组。

在我的工厂里,我有这两种功能。

function getData() {
    return $http
        .get('mock.json')
        .success(_handleData)
        .error(_handleError);
}
function _handleData(data) {
    var filteredData = _filterData(data, "name", "XYZ");
    console.log('filteredData', filteredData);
    return filteredData;
}

这里console.log("filteredData")只显示已过滤的元素(即20个中的3个);

下一个-在一项服务中,我有一个点击:

var filterMe = function () {
    DataFactory
        .getData(_address)
        .success(_handleServiceData );
}

其中

var _handleServiceData = function (data) {
    filtered = data;
};

问题是,为什么_handleServiceData中的"data"显示所有元素,而不是以前过滤的元素?

编辑:这是plunk-结果记录在控制台

因为您从_handleData函数返回的filteredData不会传递给您在filterMe函数中附加的success回调。这是因为您将回调附加在同一个promise上,因为success函数不会像then方法那样创建新的promise。所以为了解决这个问题,修改你的代码如下:

function getData() {
    return $http
       .get('mock.json')
       .then(_handleData, _handleError); //use "then" instead of "success"
}

然后在filterMe函数中:

var filterMe = function () {
    DataFactory
        .getData(_address)
        .then(_handleServiceData );
}

因为promise是异步的,并且您似乎需要在分配filtered之前将其值返回给调用者。

你应该做

function getData() {
    return $http
        .get('mock.json')
        .then(_handleData); // then (for chaining), not success!
}
var filterMe = function () {
    return DataFactory
//  ^^^^^^ return a promise, not assign globals in async callbacks
        .getData(_address)
        .catch(_handleError); // I assume you want to deal with errors only in the end
}