您好,我使用 Angular 制作視頻游戲頁面,當您單擊特定標題時,它會發送 id 以使用特定 id 進行 api 呼叫。我可以將資料放入我想使用它的選定游戲組件中,但是當我使用 ngFor 時它什么也沒顯示。沒有錯誤也沒有資料。
home 組件,您可以在其中選擇特定的視頻游戲。我將 settimeout 和路由添加到此 ts 檔案中,考慮是否可以延遲路由,直到加載選定游戲組件中的陣列但它不起作用。
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)
}
}
我試圖在 html 檔案中映射資料的選定游戲組件
game: any = [];
constructor(private getGames: FetchingVideoGamesService) { }
test(id: any){
this.getGames.functionGetGameById(id).subscribe(response =>{
this.game = response;
console.log(this.game)
})
}
}
和獲取服務
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]
}))
}
uj5u.com熱心網友回復:
您正在將子組件注入到父組件中……您不妨為此使用服務。
我建議以下方法,這是推薦的方法,一種反應式方法,讓父functionGetGameById()從服務呼叫,一旦父獲取資料,然后繼續將其發送給他的孩子。
父母
export class ParentComponent {
games$!: Observable<any[]>;
constructor(private getGames: FetchingVideoGamesService) { }
callTheService(id: string): void {
this.games$ = this.getGames.functionGetGameById(id);
}
}
父 html
...
<your-child-component [theGames]="games$ | async">
</your-child-component>
孩子
...
export class ChildComponent {
@Input() theGames!: any[];
}
子html
<div *ngFor="let game of theGames">
{{ game }}
</div>
這樣,您的組件之間保持單向通信(從上到下),父組件成為智能組件,知道邏輯業務的組件,而您的子組件成為啞組件,它只做一個非常具體的事情就是這樣,如果孩子需要向父母發送一些資料,請使用Ouput事件發射器
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484029.html
