【问题标题】:How to iterate the backend api map response in angular or typescript如何在角度或打字稿中迭代后端 api 映射响应
【发布时间】:2020-07-22 22:46:02
【问题描述】:

我有一个 api,它将返回地图响应,如 .

{thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1}

我想以角度进行迭代,但不幸的是我在尝试这个时出错了。

出现错误 ::

此表达式不可调用。类型“号码”没有电话 签名.ts(2349)

  this.testObject.forEach((value: number, key: string) => {
    console.log(key, value);
});

Iterating over Typescript Map

但我可以使用下面的代码在 html 中进行迭代..

在html中

  <div *ngFor="let item of testObject | keyvalue: originalOrder; let i=index">
    <span *ngIf="i<3">
      Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>

    </span>   
  </div>

在 .ts 文件中

testObject: { [key: string]: number };
showresult: any;

  getQuizResult(id){
    this.service.getResult(id).subscribe((stndrdResp: Response) => {
      this.showresult = stndrdResp.obj; // this will return a object
      this.testObject = this.showresult; // assigning the key value response to testObject
      });
  }

基本上我想在 getQuizResult 中迭代后端 api 响应,以便我可以执行一些操作。感谢您的宝贵建议。

【问题讨论】:

标签: angular typescript


【解决方案1】:

我想这就是你要找的东西:https://stackoverflow.com/a/24440475/12193298

评论;在上面的一个代码中,第二个参数中有key: string,但在forEach 回调中,第二个是index,它始终是一个数字。所以应该是这样的:

this.testObject.forEach((value: number, index: number) => {
    console.log(index, value);
});

【讨论】:

    【解决方案2】:

    因为testObject 是一个普通对象,而不是Map 实例。您需要创建一个映射对象或数组。

    const res = {thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1};
    var arr = Object.entries(res);//[[ "thomas", 3 ]...]
    var map = new Map(arr);//use arr or create a map
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-04
      • 2018-03-07
      • 2019-01-30
      • 2017-05-12
      • 1970-01-01
      • 2019-06-03
      • 2022-11-12
      • 2015-05-22
      相关资源
      最近更新 更多