我正在为一个角度项目绘制一个动态界面。以前我在使用动态界面方面得到了一些帮助,但是在角度上使用它似乎给了我一些问题。
我试图通过API和顶部根级的键更改,根据平台名称获取一些电子游戏数据.
// Possible platforms the user can search
enum Platforms {
'ps3',
'ps4',
'ps5',
'xbox-360',
'xbox-one',
'xbox-series-x',
'3ds',
'switch',
'pc'
}
// This interface will map out the games being returned by platform
export type GamesByPlatform = {
[key in Platforms]: {
data: Game[];
}
}在我的家庭组件中,我尝试通过订阅从游戏服务方法返回的可观察到的内容来访问这些游戏。我想获得这个接口,并访问它携带的游戏数组。此外,游戏服务方法中的“ps4”是硬编码的,用于测试目的。我主要关注的是我创建的界面的工作。
游戏服务..。
getGameList(): Observable<GamesByPlatform> {
let params = new HttpParams().set('platform', 'ps4')
.set('count', '16');
return this.http.get<GamesByPlatform>(`${env.BASE_URL}`, {
params: params
});
}家庭组件
import { Component, OnInit } from '@angular/core';
import { GamesService } from '../games.service';
import { Game, GamesByPlatform } from '../shared/models/Game';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
games: Game[] = [];
constructor(private gameService: GamesService) { }
ngOnInit(): void {
this.gameService.getGameList()
.subscribe((results: GamesByPlatform) => {
this.games = results
})
}
}我不知道如何在home组件中使用这个动态接口。如果我使用点表示法,我可以选择使用结果,results1,results2等。使用这些选项中的任何一个都会产生一个未定义的结果。我很可能需要深入研究类型记录,但我不太确定如何在我的主组件中使用这个动态接口。
发布于 2021-10-18 22:20:42
解释
问题是,您使用的枚举如下:
enum Platforms {
'ps3',
'ps4',
'ps5',
'xbox-360',
'xbox-one',
'xbox-series-x',
'3ds',
'switch',
'pc'
}相当于:
enum Platforms {
'ps3': 0,
'ps4': 1,
'ps5': 2,
'xbox-360': 3,
'xbox-one': 4,
'xbox-series-x': 5,
'3ds': 6,
'switch': 7,
'pc': 8
}你的类型
export type GamesByPlatform = {
[key in Platforms]: {
data: Game[];
}
}因此相当于
export type GamesByPlatform = {
0: { data: Game[] },
1: { data: Game[] },
2: { data: Game[] },
3: { data: Game[] },
4: { data: Game[] },
5: { data: Game[] },
6: { data: Game[] },
7: { data: Game[] },
8: { data: Game[] }
}这很可能不是你想要的。有一些方法可以解决这个问题。
解决方案1:字符串文本类型
您可以使用字符串文本类型,而不是使用枚举,如下所示:
export type Platforms = 'ps3'
| 'ps4'
| 'ps5',
| 'xbox-360',
| 'xbox-one',
| 'xbox-series-x',
| '3ds',
| 'switch',
| 'pc'
export type GamesByPlatform = {
[key in Platforms]: {
data: Game[];
}
}解决方案2:显式枚举值
另一种实现你想要的东西的方法是给你明确的价值观。
enum Platforms {
'ps3': 'ps3',
'ps4': 'ps4',
'ps5': 'ps5',
'xbox-360': 'xbox-360',
'xbox-one': 'xbox-one,
'xbox-series-x': 'xbox-series-x',
'3ds': '3ds',
'switch': 'switch',
'pc': 'pc'
}https://stackoverflow.com/questions/69621849
复制相似问题