Hello im using angular to make a video game page, when you click a specific title it sends the id to make a api call with the specific id. I can get the data into the selected-games component where i want to use it but when i use ngFor it shows nothing. no errors and no data.
home component where the you can select the specific video game. I added the settimeout and routing to this ts file thinking if i could delay the routing until the array in selected-game-component loaded but it didnt work.
constructor( private getGame: SelectedGameComponent, private router: Router) { }
ngOnInit(): void {
}
sendId(id: any){
// this.gamesService.functionGetGameById(id);
this.getGame.test(id);
setTimeout( () => {
this.router.navigateByUrl('game')
}, 5000)
}
}
The selected game component where im trying to map the data in the html file
game: any = [];
constructor(private getGames: FetchingVideoGamesService) { }
test(id: any){
this.getGames.functionGetGameById(id).subscribe(response =>{
this.game = response;
console.log(this.game)
})
}
}
and the fetch service
functionGetGameById(id: any){
return this.http.get<any>('https://api.rawg.io/api/games/' id '?key=keyremovedforpost'
)
.pipe(map(response =>{
const gameArray: any = [];
gameArray.push(response)
console.log(gameArray, 'response from service')
return gameArray[0]
}))
}
CodePudding user response:
You are injecting a child component into the parent component... you might as well use a service for that.
I suggest the following approach, which is the recommended one, a reactive approach, let the parent call functionGetGameById()
from the service, once the parent gets the data back, then proceeds to send it to his child.
parent
export class ParentComponent {
games$!: Observable<any[]>;
constructor(private getGames: FetchingVideoGamesService) { }
callTheService(id: string): void {
this.games$ = this.getGames.functionGetGameById(id);
}
}
parent html
...
<your-child-component [theGames]="games$ | async">
</your-child-component>
child
...
export class ChildComponent {
@Input() theGames!: any[];
}
child html
<div *ngFor="let game of theGames">
{{ game }}
</div>
With this, you keep one-way communication between your components (top to bottom), the parent component becomes a smart component, the one that knows about the logic business, while your child component becomes a dumb component, it only does a very specific thing and that's it, if the child needs to send back some data to the parent, use an Ouput
event emitter