简体   繁体   中英

Instantiate object from JSON API call array?

Okay say I have a class like this in 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 }

Then I make my api Call that returns an array of games. In a class that looks something like this.

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 }

So this obviously works but it doesn't instantiate the objects. So if call the getter getName() in a situation like this (in another component).

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

It throws an error like TypeError: _v.context.$implicit.getName() is not a function

but if I change the instance variable to public is works like this.

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

But I'm pretty sure that only works because i'm just type checking and its not creating an instance of a game... Is what i'm doing even worth it? I'm trying to implement better practices and move away from procedural programming.

Use rxjs to pipe a map which will return directly the array of your instances.

So your code should look something like:

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));
}

So:

  1. fetch the games
  2. pipe a map which will transform all your data returned by the api into an array of Game instances
  3. Now in your subscribe you have directly the array of games as Game instances

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM