javascript - 从 JSON API 调用数组实例化对象?

标签 javascript angular typescript

好吧,假设我在 Angular 6 中有这样一个类:

export class Game {
 private readonly iD: number;
 private readonly name: string;
 private readonly genre: string;

constructor (iD: number,
        name: string,
        genre: string) {
    this.iD = iD;
    this.name = name;
    this.genre = genre;
}

getName(): string { return this.name }

然后我进行 api 调用,返回一系列游戏。在一个看起来像这样的类中。

interface ApiGames {
  games: Game[];
}

@Injectable({
 providedIn: 'root'
})
export class GameRepository {
  private game: Game;
  private games: Game[] = [];

constructor(private ApiService: ApiService) {
}

retrieveGames(): void {
this.ApiService.getGames()
  .subscribe(
    (response: ApiGames) => {
      this.games = response.games;
      }
 );
}

getGames(): Game[] { return this.games }

所以这显然有效,但它没有实例化对象。因此,如果在这种情况下(在另一个组件中)调用 getter getName()。

<div *ngFor="let game of gameRepository.getGames()">
 {{ game.getName() }}
</div>

它抛出类似 TypeError: _v.context.$implicit.getName() is not a function 的错误

但是如果我将实例变量更改为 public 就是这样工作的。

<div *ngFor="let game of gameRepository.getGames()">
 {{ game.name }}
</div>

但我很确定这只是有效的,因为我只是进行类型检查,而不是创建游戏实例……我正在做的事情值得吗?我正在尝试实现更好的做法并摆脱过程编程。

最佳答案

使用 rxjs 来传输一个 map ,它会直接返回你的实例数组。

所以你的代码应该是这样的:

retrieveGames(): void {
  this.ApiService.getGames()
    .pipe(
      map((response: ApiGames) => response.games.map(g => 
        new Game(g.id, g.name, g.genre)
      ))
    )
    .subscribe((games: Game[]) => console.log('games:', games));
}

所以:

  1. 获取游戏
  2. 通过管道将 api 返回的所有数据转换为 Game 实例数组
  3. 现在在您的订阅中,您直接拥有作为 Game 实例的游戏数组

关于javascript - 从 JSON API 调用数组实例化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297547/

相关文章:

javascript - 掷骰子游戏的重置功能

javascript - 如何处理 React Router 递归路径?

javascript - Angular JS - "Error: [$interpolate:interr] Can' t 插值 :"when using Highcharts

java - JSTL:如何获取Map的上一个和下一个迭代元素?

angular - 使用 Angular 浏览静态 Html 文件

Angular 2 : ReactiveForm Updating Model

java - 如何在 ionic 3 应用程序启动屏幕上设置自定义微调器

html - Angular - Material 表,是否可以通过单击按钮来编辑行?

javascript - 类型错误 : Repository method is not a function (NestJS/TypeORM)

具有 BehaviorSubject 的 Angular api 服务不会实时刷新组件数据