我从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个);
接下来 - 在一项服务中,我已经通过ng-click获得了这个:
var filterMe = function () {
DataFactory
.getData(_address)
.success(_handleServiceData );
}
,其中
var _handleServiceData = function (data) {
filtered = data;
};
事情是 - 为什么'数据'在_handleServiceData中显示所有元素而不是先前过滤的那些元素?
编辑:here's the plunk - 结果记录在控制台
中答案 0 :(得分:2)
因为您从filteredData
函数返回的_handleData
未传递到您在success
函数中附加的filterMe
回调。那是因为你在同一个承诺上附加了回调,因为success
函数不像then
方法那样创建新的承诺。所以要解决这个问题,请修改你的代码:
function getData() {
return $http
.get('mock.json')
.then(_handleData, _handleError); //use "then" instead of "success"
}
然后在filterMe
函数:
var filterMe = function () {
DataFactory
.getData(_address)
.then(_handleServiceData );
}
答案 1 :(得分:1)
因为promises是异步的,并且您似乎将filtered
的值返回给调用者before it could be assigned。
你应该这样做
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
}