arrays - Ionic 4:helperService 中的“Typescript 错误”无法读取 HelperService 中未定义的属性“长度”
问题描述
尝试循环遍历已作为 helperService 类 [Typescript] 中的参数传递的数组时,出现错误“无法读取 HelperService.addCommasToArray 未定义的属性“长度”
我真的不确定为什么这不起作用-我相信它应该很简单-我要做的就是将数组作为参数传递并为数组中的每个值添加一个“,”(除了最后一个价值)
这是我的 HelperService 类方法:
export class HelperService {
constructor() { }
/*
* Add commas to every value in the array except for the last value
*/
addCommasToArray(array: Array<any>) : Array<any> {
for (let i = 0; array.length; i++){
array[i] += ", ";
}
return array;
}
}
然后我在另一个 ts 类的 ngInit 中调用这个方法
this.helperService.addCommasToArray(this.previousClubs);
这是 ngInit 方法
public previousClubs: Array<any>;
constructor(private playersService: PlayersService,private
helperService: HelperService, private route: ActivatedRoute) { }
ngOnInit() {
const playerId: string = this.route.snapshot.paramMap.get('id');
this.playersService.getPlayerDetails(playerId).get()
.then(playerDetailsSnapshot=> {
this.currentPlayerDetails = playerDetailsSnapshot.data();
this.currentPlayerDetails.id = playerDetailsSnapshot.id;
});
/*
* Return Previous Clubs
*/
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
this.helperService.addCommasToArray(this.previousClubs);
}
解决方案
所以在这里:
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
// this line executes without awaiting for .then enclosed scope
this.helperService.addCommasToArray(this.previousClubs);
基本上,您甚至在您的 previousClubs var 获取分配给它的数组然后将其所有项目推入之前调用 addCommasToArray。由于您的方法是 (.then) 异步的,因此您需要在 .then 执行范围内调用此方法:
ngOnInit() {
const playerId: string = this.route.snapshot.paramMap.get('id');
this.playersService.getPlayerDetails(playerId).get()
.then(playerDetailsSnapshot=> {
this.currentPlayerDetails = playerDetailsSnapshot.data();
this.currentPlayerDetails.id = playerDetailsSnapshot.id;
});
/*
* Return Previous Clubs
*/
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
this.helperService.addCommasToArray(this.previousClubs);
}
推荐阅读
- c# - 观察并删除(截图),如果在 Iphone 中使用我的应用程序时截取了屏幕截图
- duplicates - 邮递员重复收集/导出+重新导入
- django - 将数据填充到模型表单 Django 并在 URL Django 中传递 id 参数
- java - M2_HOME 将其路径设置为 bin
- corda - Corda 线性状态唯一性
- android - 为什么相对布局展开时framelayout内容消失
- python - 如何计算嵌套列表中两个项目的出现次数
- javascript - 验证字符串以匹配数字/浮点数
- agora.io - 加入()函数加载页面在移动设备上不起作用
- java - 如何在休眠中修复此查询?