首页 > 解决方案 > 捕获http json主体响应并转换为角度ionic5中的数组

问题描述

我被卡住了,在环顾这里和其他页面时,我找不到合适的东西:/我想要的是提取它并以一种我可以用来在 html 中构建一个简单表格的方式让它看起来像

回复 数数
[价值] [价值]
[价值] [价值]

并以列表格式将其设置为稍后在 chart.js 中使用,但这将在稍后进行。

(仅供参考,我不是开发人员,一直在学习——但我擅长乐高 :) 所以连接积木和适应是我学习编码的方法,如果初学者有问题,我深表歉意 :))

所以,我有一个 http 调用 (GET) 工作。它返回正文:

[
  {
    "response": "Yes",
    "count": 1
  },
  {
    "response": "No",
    "count": 1
  }
]

但我不知道如何使用它......

我的http服务查询:

getPollResults(pollId): Observable<Pollresults>{
      return this.http
      .get<Pollresults>(this.base_path + '/polls/responses/' + pollId)
      .pipe(
        retry(2),
        catchError(this.handleError)
      )
  }

我的 Pollresults 模型:

export class Pollresults {

    response: string;
    count: number;

}

我的组件 page.ts 调用似乎捕获了数据,但后来我被困在如何使用它上......

 export class PollResultsPage implements OnInit {

   uid: string;
   dataPollresults: Pollresults;

   constructor(
     private httpConfigService: HttpConfigService
   ) { }

   ngOnInit() {
      // this.id = this.activatedRoute.snapshot.params["id"];
      this.uid = "alphapoll";
      //get item details using id
      this.httpConfigService.getPollResults(this.uid).subscribe(response => {
      console.log(response);
      this.dataPollresults = response;
      //data => resolve(Object.keys(data).map(key => data[key]))
         })
   }

有关如何正确提取和获取数组的任何帮助?以及如何将其添加到 html 中?

非常感谢你的帮助。

标签: arraysjsonangulartype-conversionconverters

解决方案


改变这个

getPollResults(pollId): Observable<Pollresults>{
  return this.http
  .get<Pollresults>(this.base_path + '/polls/responses/' + pollId)
  .pipe(
    retry(2),
    catchError(this.handleError)
  )

}

对此

getPollResults(pollId): Observable<Pollresults[]>{
  return this.http
  .get<Pollresults>(this.base_path + '/polls/responses/' + pollId)
  .pipe(
    retry(2),
    catchError(this.handleError)
  )

}


推荐阅读