簡體   English   中英

從 JSON API 調用數組實例化對象?

[英]Instantiate object from JSON API call array?

好吧,說我在 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 Call 返回一系列游戲。 在一個看起來像這樣的班級。

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 ,該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實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM