我有以下代码,它尝试读取txt,将其转换为数组,然后将其转换为json,以将其保存在db中,但是在调用控制器时,我尝试运行SaveReferences函数,向我发送此错误: UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ service”
另外,请给我发送此邮件:Promise { TypeError:无法读取ReferenceController上的GetingInfo.Readfile处的GetingInfo.SaveReferences处未定义的属性“服务”
export interface Dataconf{
service:number;
name:string;
ref:string
}
export class GettingInfo {
constructor(private referenceService: ReferenceService) {
}
Readfile = () => {
const file = path.resolve(__dirname, '../../../dist/entity/PRUEBA.txt')
try {
const data = fs.readFileSync(file, 'utf-8');
const lines = data.split("\n")
let values = []
let bi = []
lines.forEach(line => {
line.trim()
values = line.split("\|", 6).map(a => a.trim());
bi.push(values)
console.log(bi)
})
const convert = this.ConditionData(bi)
console.log(convert)
const save = this.SaveReferences(convert)
console.log(save)
} catch (err) {
console.error(err), "something has happened to the file";
}
}
ConditionData(values): Array<Dataconf> {
let resultado = [];
values.forEach(arreglo => {
let ref = 'ref';
for (let i = 3; i < arreglo.length; i++) {
if (arreglo[i].length > 0) {
let obj = {
service: parseInt(arreglo[0]),
name: arreglo[1]
}
obj[ref] = arreglo[i];
resultado.push(obj);
}
}
});
console.log("resultado funcionConditionData", resultado)
return resultado;
}
async SaveReferences(data: Array<Dataconf>) {
console.log("array", data)
let i
let orderField = 0;
let helper = data[i].service;
for (i = 0; i <= data.length; i++) {
if (data[i].service != helper) {
helper = data[i].service;
orderField = 0
try {
let res = await this.referenceService.createReference({
service: data[i].service,
name: `ref${i}`,
label: data[i].ref,
longitud: 0,
order: orderField
});
} catch (e) {
console.error(e);
}
}
}
return data;
}
答案 0 :(得分:1)
在SaveReferences的第四行i
中未定义
let helper = data[i].service;
应该是
let helper;
由于在for循环中分配了助手,因此
答案 1 :(得分:0)
**let i
let orderField = 0;
let helper = data[i].service;**
此代码块引起错误。您声明了i
,但没有初始化它。因此它的默认值为undefined
。然后,您尝试做data[i].service
转换为data[undefined].service