Typescript / Angular 7:如何迭代匹配我的接口与 Object.keys 的对象?

Typescript / Angular 7: How can I iterate over Object matching my Interface with Object.keys?

我对 Javascript 和 Typescript/Angular 很陌生..

我正在从网站获取数据/游戏统计信息以制作我自己的统计应用程序。我已经创建了一个定义了 Key/Values 的接口来匹配我想在我的模板上显示的数据。

我希望以嵌套对象的形式显示API的响应。因此,我使用 Object.keys() 来遍历对象,并在我的 HTML 模板上显示结果。

我能够很好地显示特定嵌套对象的 JSON。我的问题是:它显示了该对象的整个 Key/Values,而不是我在界面中定义的特定键值。

在我的 HTML 中,我正在循环调用名为 lifeTimeStat Object.keys(lifeTimeStat) 的界面 -(另请参阅下面的完整内容 html)

看到我需要如何遍历一个对象,我试图让我的 lifeTimeStat 接口成为一个对象。像这样:

`export class CombatListComponent implements OnInit {

constructor(public combatService: CombatService) { }

lifeTimeStats: lifeTimeStat = {
headshotKills: null,
             kills: null,
             longestKill: null, 
             maxKillStreaks: null,
             dailyKills: null,
             weeklyKills: null,
             damageDealt: null,
             roadKills: null,
             teamKills: null,
              vehicleDestroys: null,
              suicides: null,
              roundMostKills: null,
              dBNOs: null,
              assists: null
  } 


ngOnInit() {
this.combatService.getCombat().subscribe(data => {this.lifeTimeStats = 
data} );  
}
}

`

但是,当然,我收到了这个错误:TypeError: Cannot read property 'keys' of undefined ..所以我似乎没有以正确的方式将我的接口变成对象..

让 JSON 在我的 HTML 中显示的唯一方法是我改为定义 Object = Object 而不是那种将我的界面变成对象的蹩脚尝试。啊。 Object = Object 只会显示整个对象,而不是我的界面的特定形状..

HTML: 战斗-list.component.html <div *ngFor="let key of Object.keys(lifeTimeStat)"> {{ lifeTimeStats[key].attributes.gameModeStats.solo| json }} </div> <br>

服务组件:combat.service.ts

`@Injectable({
  providedIn: 'root'
})
export class CombatService {
getCombat():Observable<lifeTimeStat> {

return this.http.get<lifeTimeStat>(this.configUrl,  { observe:'body',   
responseType: 'json', headers: getHeaders });    

}`

接口:

    `export interface lifeTimeStat {


            headshotKills: number,
             kills: number,
             longestKill: number, 
             maxKillStreaks: number,
             dailyKills: number,
             weeklyKills: number,
             damageDealt: number,
             roadKills: number,
             teamKills: number,
              vehicleDestroys: number,
              suicides: number,
              roundMostKills: number,
              dBNOs: number,
              assists: number,



}  `

我只想显示我在界面中定义的选定数据。在将近两天的时间里,我在 SO 上搜索/搜索了很多小时:(

所以这个语法应该有效:

Object
  .keys({ a: 1, b: 2 })
  .map(key => console.log(key));

如果不是,为什么不将数组分配给一个变量并遍历该变量?

在任何情况下,您都可以使用这个好帮手来保留类型并迭代键和值:

const testObject = {
  completed: true,
  score: 129.1,
  description: 'none',
};

entries(testObject)
 .map(([key, value]) => console.log(`Key is ${key}, value is ${value}`));

function entries<K>(object: K)  {
    return (Object.keys(object) as (keyof K)[])
        .filter((key) => object[key] !== undefined && object[key] !== null)
        .map(
            key => ([
                key,
                object[key],
            ] as [keyof K, Required<K>[keyof K]]),
    );
}

type Required<T> = {
    [P in keyof T]-?: T[P];
};

或者您的情况:

const keyValuePairs = entries(lifeTimeStat);

...

<div *ngFor="const [key, value] of keyValuePairs">    {{ value.attributes.gameModeStats.solo| json }}  </div> <br>