我试图在Angular中创建一个虚拟模型以从后端获取值。但这会由于数组而引发一些错误。
abc.ts
export class abc {
date: Date;
time: string;
ABC_Info: [{
item: string,
quantity: number,
a: number
},
{
item: string,
quantity: number,
a: number
}
]
constructor(date: Date, time: string, item: string, quantity: number, a: number) {
this.meal_time = meal_time;
this.date = date;
this.time = time;
this.ABC_Info[0].item = item;
this.ABC_Info[0].quantity = quantity;
this.ABC_Info[0].carbs = a;
this.ABC_Info[1].item = item;
this.ABC_Info[1].quantity = quantity;
this.ABC_Info[1].carbs = a;
}
}
abc.service.ts
import { abc} from './models/abc';
getABCs(start ? : moment.Moment, end ? : moment.Moment): Observable < abc[] > {
let params = new HttpParams();
if (start) {
params = params.append('start', start.toISOString());
}
if (end) {
params = params.append('end', end.toISOString());
}
return this.baseService.getParams('/api/abc/getAll', params)
.pipe(
map(res => res as Object[] || []),
map(bolus => bolus.map(k => new abc(
new Date(k['date']),
k['time'],
k['item'],
k['quantity'],
k['a']))
)
)
}
浏览器控制台错误
错误TypeError:无法读取未定义的新属性'0' Bolus(abc.ts:39)在abc.service.ts:33在Array.map(<匿名>) 在MapSubscriber.project(carb.service.ts:33)处。 / node_modules / rxjs / _esm5 /内部/运算符/ /位于MapSubscriber.push处的map.js.MapSubscriber._next(map.js:35)。/ node_modules / rxjs / _esm5 /内部/ Subscriber.js.Subscriber.next(Subscriber.js:54)位于 MapSubscriber.push ../ node_modules / rxjs / _esm5 /内部/ 运算子/ map.js.MapSubscriber._next(map.js:41)位于 MapSubscriber.push ../ node_modules / rxjs / _esm5 /内部/ Subscriber.js.Subscriber.next(Subscriber.js:54)位于 MergeMapSubscriber.push ../ node_modules / rxjs / _esm5 /内部/ 运算子/ mergeMap.js.MergeMapSubscriber.notifyNext(mergeMap.js:84) 在InnerSubscriber.push ../ node_modules / rxjs / _esm5 /内部/ InnerSubscriber.js.InnerSubscriber._next(InnerSubscriber.js:15)
答案 0 :(得分:1)
这是定义模型的方法:
export interface Abc {
date: Date;
time: string;
ABC_Info: {item: string, quantity: number, a: number}[]
}
然后在您的http服务中:
getAbc(): Observable<Abc> {
return this.http.get('some api').pipe(map(res => res.json)); // Remove pipe if angular version is below 6
}
答案 1 :(得分:0)
您应该尝试以下操作: Angular 2 declaring an array of objects
在我看来,您正在尝试为数组定义一种类型,但同时也试图为两个对象创建空间,这不是您应该做的(请参阅链接)。
您遇到的错误是因为当您尝试访问0索引时未初始化数组(通过带有断点的控制台检查,您会看到数组未定义)。