AngularJs将参数传递给then

时间:2017-03-18 19:36:10

标签: javascript angularjs

我有一个脚本正在获取项目列表然后每个项目我获得数据然后需要将定义和数据组合到一个对象

代码中的部分: 我想将itemObject传递给DashboardFactory.Convert函数

这可能吗?还是有更好的方法来解决这个问题?

目前,由于承诺机制

,它具有items数组中最后一项的值
var items = BaseFunctionsService.GetData(result);
console.log('success', items);
if (items)
{
    var itemdata = null;
    var chartData = null;
    var itemData = null;
    var itemObject = null;

    for (var i = 0; i < items.length; i++) {
        itemObject = items[i];
        itemData = DashboardFactory.GetData(items[i]);

        itemData.then(function (result) {
            console.log('itemdata result', result);
            itemdata = BaseFunctionsService.GetData(result);
            chartData = DashboardFactory.Convert(itemObject, itemdata, result.data.Translations[result.data.LangKey]);
            console.log('itemdata success', chartData);
            $scope.data.push(chartData);
        }, function (error) {
            console.log('itemdata error', error);
        });
    }
    console.log('data output', $scope.data);
}

1 个答案:

答案 0 :(得分:0)

您需要在for循环中使用IIEF,以便在解析itemObject promise时保持对itemData的正确引用,这是for循环中闭包的常见错误。

var items = BaseFunctionsService.GetData(result);
console.log('success', items);
if (items)
{
    var itemdata = null;
    var chartData = null;
    var itemData = null;
    var itemObject = null;

    for (var i = 0; i < items.length; i++) (function (i) {
        itemObject = items[i];
        itemData = DashboardFactory.GetData(items[i]);

        itemData.then(function (result) {
            console.log('itemdata result', result);
            itemdata = BaseFunctionsService.GetData(result);
            chartData = DashboardFactory.Convert(itemObject, itemdata, result.data.Translations[result.data.LangKey]);
            console.log('itemdata success', chartData);
            $scope.data.push(chartData);
        }, function (error) {
            console.log('itemdata error', error);
        });
    })(i);
    console.log('data output', $scope.data);
}