将JSON数据检索到类数组中
我试图从下面的文件中检索数据,返回一个带有json值的类对象,并将其推送到上面的类数组中以显示为硬编码的json数据,当前错误是无法将Exercise[]分配给Exercise。我对编码还不熟悉,我真的很感谢能伸出援助之手的人将JSON数据检索到类数组中,json,angular,http,ionic-framework,angular8,Json,Angular,Http,Ionic Framework,Angular8,我试图从下面的文件中检索数据,返回一个带有json值的类对象,并将其推送到上面的类数组中以显示为硬编码的json数据,当前错误是无法将Exercise[]分配给Exercise。我对编码还不熟悉,我真的很感谢能伸出援助之手的人 export class ExerciseService { exercises: Exercise[] = [] completedEx: Exercise[] = [] errorMessage: string; constructor(privat
export class ExerciseService {
exercises: Exercise[] = []
completedEx: Exercise[] = []
errorMessage: string;
constructor(private http: HttpClient) {
// this.exercises = [
// new Exercise('pull-ups', 3, 5, '1/1/2020', '13:00', 'assets/pullups.jpg', 'pull-ups'),
// new Exercise('push-ups', 3, 20, '2/2/2020', '14:00', 'assets/pushups.jpg', 'push-ups'),
// new Exercise('sit-ups', 3, 30, '3/3/2020', '15:00', 'assets/situps.jpg', 'sit-ups')
// ]
this.getExerciseData().subscribe(data=> this.exercises.push(data))
}
getExercises(): Exercise[] {
return this.exercises;
}
getExerciseData(){
return this.http.get("/assets/data/exerciseData.json").pipe
(map(response => Object.keys(response["exercises"]).map(function(key, index){
let row = response["exercises"][key]
return new Exercise(key, row["sets"], row["reps"], row["date"], row["time"], row["image"], key)
})))
}
//json file
{
"exercises": {
"Pull-ups": {
"name": "Pull-ups",
"sets": 3,
"reps": 6,
"date": "2/2/2020",
"time": "16:00",
"image": "assets/pullups.jpg",
"id": "Pull-ups"
},
"Push-ups": {
"name": "Push-ups",
"sets": 3,
"reps": 20,
"date": "10/2/2020",
"time": "14:00",
"image": "assets/pushups.jpg",
"id": "Push-ups"
},
"Sit-ups": {
"name": "Sit-ups",
"sets": 5,
"reps": 30,
"date": "12/2/2020",
"time": "13:00",
"image": "assets/situps.jpg",
"id": "Sit-ups"
}
}
}
//exercise class
export class Exercise {
name: string
reps: number
sets: number
date: string
time: string
image: string
id: string
constructor(name: string, sets: number, reps: number, date: string, time: string, image: string, id?: string) {
this.name = name
this.sets = sets
this.reps = reps
this.date = date
this.time = time
this.image = image
this.id = id
}
}
将您的构造函数代码更改为:-
constructor(private http: HttpClient) {
this.getExerciseData().subscribe(data=> {
this.exercises = [...this.exercises, ...data]);
});
}
将GetExercise方法更改为:-
getExerciseData(){
return this.http.get("/assets/data/exerciseData.json").pipe
(map(response => Object.keys(response["exercises"]).map((key, index) =>{
let row = response["exercises"][key]
return new Exercise(key, row["sets"], row["reps"], row["date"], row["time"], row["image"], key)
})))
}
什么是exercise类的构造函数?@AakashGarg很抱歉,我完全忘记添加它了,我现在已经添加了从
getExerciseData()
函数返回的数据已经是一个包含exercise
类的三个对象的数组。您需要在订阅中执行data=>this.exercises=[…this.exercises,…data]
。关于spread运算符(…
)的更多信息,请看这里:嗨,Aakash,练习数组仍然没有填充JSON对象,我试图在另一个tabupdated语句上使用getExecuts()函数,忘记将其分配回练习:Pstill出于某种原因没有填充复制整个语句,和console.log作为下标的秒语句。数据将在那里。我尝试记录练习数组及其直到空,即使在下一页编辑:对不起,如果我看起来特别慢,这是我的头几个月的编码,我感谢所有的帮助