我有角度ui网格,我试图从其细胞中获取值。这是表格中的列表
id name
1 AUSTRIA
2 BELGIUM
3 BULGARIA
4 CROATIA
5 CZECH REPUBLIC
这是我运行的代码:
element(by.id('grid1')).all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index')).then(function (items) {
for (var i = 0; i < items.length; i++) {
var country = <any>{}; //typescript code
self.gridTestUtils.dataCell('grid1', i, 0).getText().then(
function (valueId) {
country.id = valueId
});
self.gridTestUtils.dataCell('grid1', i, 1).getText().then(
function (valueName) {
country.name = valueName;
self.countryList.push(country)
console.log(self.countryList)
});
}
});
这是结果
[ { id: 1, name: 'AUSTRIA' }]
[ { id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BELGIUM' }]
[ { id: 1, name: 'BULGARIA' },
{ id: 1, name: 'BULGARIA' },
{ id: 1, name: 'BULGARIA' } ]
[ { id: 1, name: 'CROATIA' },
{ id: 1, name: 'CROATIA' },
{ id: 1, name: 'CROATIA' },
{ id: 1, name: 'CROATIA' } ]
[ { id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' } ]
我希望结果如下:
[ { id: 1, name: 'AUSTRIA' }]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' }]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BULGARIA' } ]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BULGARIA' },
{ id: 1, name: 'CROATIA' } ]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BULGARIA' },
{ id: 1, name: 'CROATIA' },
{ id: 1, name: 'CZECH REPUBLIC' } ]
我的代码出了什么问题?我应该做什么,我期待数组
答案 0 :(得分:0)
问题是你的循环中的i
会随着循环的进行而发生变化,而在你的异步调用中,你正在使用i
并获得一个承诺,但它只是一个参考,因此,当promises得到解决时,将使用循环的最后一个值来引用变量。解决方法是创建IIFE:
element(by.id('grid1')).all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index')).then(function (items) {
for (var i = 0; i < items.length; i++) {
var country = <any>{}; //typescript code
(function (i, country) {
self.gridTestUtils.dataCell('grid1', i, 0).getText().then(function (valueId) {
country.id = valueId;
});
self.gridTestUtils.dataCell('grid1', i, 1).getText().then(function (valueName) {
country.name = valueName;
self.countryList.push(country)
console.log(self.countryList)
});
})(i, country);
}
});