简体   繁体   中英

Filtering and $http promises in Angular

I've got a problem with filtering data from JSON file, which is an array of 20 objects.

in my factory I have these two functions.

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

and here console.log("filteredData") shows only filtered elements (ie 3 out of 20);

next - in a service I've got this one on ng-click:

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

where

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

the thing is - why the 'data' in _handleServiceData shows all of the elements instead of these previously filtered?

edit: here's the plunk - results are logged in console

Because the filteredData you return from _handleData function is not passed to the success callback you attach in filterMe function. That's because you attach that callback on the very same promise, since success function doesn't create new promise like the then method does. So to solve this modify your code like this:

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

Then in filterMe function:

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

Because promises are asynchronous, and you seem to return the value of filtered to your caller before it could be assigned .

You should be doing

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM