我是 Angular (12) 的初學者,我正在努力解決這個問題。我想在頁面上顯示多個隨機參考。我設法顯示了多個,但它們在彼此之下都是相同的。我在代碼中沒有錯誤。我已經嘗試了一些 forEach 但無法做到。這是代碼:
應用程式組件.html
<div class="main-content">
<div class="joke-wrapper" *ngFor="let joke of jokes">
<div class="joke">
<p>{{ joke.value }}</p>
</div>
</div>
<div class="joke-wrapper" *ngFor="let joke of jokes">
<div class="joke">
<p>{{ joke.value }}</p>
</div>
</div>
</div>
笑話.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class JokesService {
private apiUrl = 'https://api.chucknorris.io/jokes/';
constructor(private http: HttpClient) {}
getRandomJoke() {
return this.http.get(this.apiUrl 'random');
}
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { JokesService } from './jokes.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
jokes: any[] = [];
constructor(private jokesService: JokesService) {}
ngOnInit() {
this.jokesService.getRandomJoke().subscribe((joke) => {
this.jokes.push(joke);
});
}
}
uj5u.com熱心網友回復:
問題是你的陣列只包含一個笑話。
這可能有效。
import { Component, OnInit } from '@angular/core';
import { JokesService } from './jokes.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
jokes: any[] = [];
constructor(private jokesService: JokesService) {}
ngOnInit() {
// Multiple times
this.addJoke();
this.addJoke();
}
addJoke() {
this.jokesService.getRandomJoke().subscribe((joke) => {
this.jokes.push(joke);
});
}
}
雖然我更喜歡這個解決方案:
使用async管道可以獲得一些性能提升,它通常是更干凈的代碼。
組件 ts:
import { Component, OnInit } from '@angular/core';
import { JokesService } from './jokes.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
jokes$!: Observable<any[]>;
constructor(private jokesService: JokesService) {}
ngOnInit() {
this.jokes$ = this.jokesService.getRandomJokes(10);
}
}
服務:
@Injectable({
providedIn: 'root',
})
export class JokesService {
private apiUrl = 'https://api.chucknorris.io/jokes/';
constructor(private http: HttpClient) {}
getRandomJoke() {
return this.http.get(this.apiUrl 'random');
}
getRandomJokes(amount: number) {
const jokes = [];
for (let i = 0; i < amount; i ) {
jokes.push(this.getRandomJoke())
}
return forkJoin(jokes);
}
}
組件html:
<div class="main-content">
<div class="joke-wrapper" *ngFor="let joke of jokes$ | async">
<div class="joke">
<p>{{ joke.value }}</p>
</div>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/347717.html
上一篇:如何擺脫頁面右側的空白?
