[英]Angular, Converting JSON , Rxjs Opertaor, Typescript
I received the following object ( Survay ) JSON format from server我从服务器收到了以下 object ( Survay ) JSON 格式
/**************************************/ /******************************************/
{
"id": 870,
"title": "test survay ",
"questions": [
{
"id": 871,
"data": "question data 1"
},
{
"id": 874,
"data": "question data 2"
},
{
"id": 877,
"data": "question data 3"
}
],
"user": {
"id": 788,
"name": "mohamed",
"answres": [
{
"data":"answere question 1"
},
{
"data":"answere question 2"
},
{
"data":"answere question 3"
}
]
}
}
I used the following code我使用了以下代码
getSurvayByid(id: number) {
const headers = new HttpHeaders({
'Authorization': this.loadToken(),
'Content-Type': 'application/json'
});
return this.http.get<Survay>(this.host + "/survay/" + id, { headers: headers })
.pipe(map(resp => resp));
}
I would like to change this format as it's displayed:我想在显示时更改此格式:
My question:how I can get this format using the Rxjs operators?我的问题:如何使用 Rxjs 运算符获得这种格式? (map, take, pipe...) and change the method getSurvayByid(id: number)
(map, take, pipe...) 并更改方法getSurvayByid(id: number)
{
"id": 870,
"title": "test survay ",
"questions": [
{
"id": 871,
"data": "question data 1",
"answer":"answere question 1"
},
{
"id": 874,
"data": "question data 2",
"answer":"answere question 2"
},
{
"id": 877,
"data": "question data 3",
"answer":"answere question 3"
}
],
"user": {
"id": 788,
"name": "mohamed"
}
}
Assuming the answers are in correct order, you can do it like this:假设答案的顺序正确,您可以这样做:
return this.http.get<Survay>(this.host + "/survay/" + id, { headers: headers }).pipe(
map((resp: Survay): Survay => {
resp.questions.forEach((question, i) => question.answer = resp.answers.length == 0 ? '' : resp.answers[i].data);
return resp;
})
);
I'm assuming the return type is also Survay
.我假设返回类型也是
Survay
。 Please replace with correct return type.请用正确的返回类型替换。
getSurvayByid(id).toPromise().then(s => {
s.questions.forEach((q,i)=>{this.answers=s.user.answres!
if(this.answers.length==0){
q.answer="";
}
else {
q.answer=this.answers[i].data;
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.