我在使用 *ngFor 顯示資料時遇到問題:
拍賣物件包含出價陣列。
export interface Auction {
descripton: string;
sellerId: string;
title: string;
price: number;
quantity: number;
bids: Bid[];
boughtByList: string[];
photoAlbum: PhotoAlbumModel;
auctionType: string;
starts: Date;
ends: Date;
comments: Comment[];
}
export class Bid {
constructor(public amount: number, public userName: string, public productTitle: string) {
}
}
我在 AuctionDetailsComponent 中獲取拍賣資料
export class AuctionDetailsComponent implements OnInit, OnDestroy {
private title: string;
auction: Auction;
bid: Bid;
bidResponse: BidResponse;
highestBid: number;
coins: number;
private paramsSubscription: Subscription;
imageObjects: Array<object> = [];
constructor(private router: Router,
private activatedRoute: ActivatedRoute,
private productService: ProductService,
private cartService: CartService,
private authService: AuthenticationService,
private auctionService: AuctionService) {
}
ngOnInit(): void {
this.paramsSubscription = this.activatedRoute.params
.subscribe((params: Params) => {
this.title = params.title;
this.getAuction(this.title);
});
}
getAuction(title: string) {
this.auctionService
.get(title)
.subscribe((auction) => {
this.auction = auction;
this.setImageObject();
});
}
在 auction-details.component.html 我嘗試使用 *ngFor 顯示出價資料
<div *ngFor="let bid of auction.bids">
<p>{{bid.userName}}</p>
</div>
段落為空,但在 chrome 除錯中有一個陣列。

和其他拍賣資料 - 標題、價格顯示正常。
我不知道問題出在哪里。
uj5u.com熱心網友回復:
避免subscribing進入Observable內部.ts檔案,而是使用async pipe,嘗試這樣寫:
async ngOnInit(): void {
const params = await lastValueFrom(this.activatedRoute.params);
this.title = params.title;
this.action$ = this.auctionService.pipe(tap(() => this.setImageObject()))
}
然后在模板中你可以使用async pipe
<div *ngFor="let bid of (auction$ | async)?.bids">
<p>{{bid.userName}}</p>
</div>
祝你好運 :)
uj5u.com熱心網友回復:
存在異步等待問題。確保在 Angular 應用程式上顯示資料之前加載資料。另外,我認為您可以在加載頁面后使用 ngOnChanges 生命周期掛鉤來加載資料。
uj5u.com熱心網友回復:
據我了解,當我初始化 html Auction 不是
ngOnInit(): void {
this.paramsSubscription = this.activatedRoute.params
.subscribe((params: Params) => {
this.title = params.title;
this.getAuction(this.title);
console.log(this.getAuction(this.title)); // undefined
});
}
getAuction(title: string) {
this.auctionService
.get(title)
.then((auction) => {
this.auction = auction;
this.setImageObject();
});
}
我試圖將 getAuction 更改為異步功能,但問題仍然存在。
async get(title: string): Promise<any> {
return this.http
.get<Auction>(this.AUCTION_URL title, this.getAuth()).toPromise();
}
uj5u.com熱心網友回復:
我試過這樣但 ngOnInit() 不啟動
async ngOnInit(): Promise<void> {
const params = await lastValueFrom(this.activatedRoute.params);
this.title = params.title;
this.auction$ = this.auctionService.get(this.title);
}
在此處輸入影像描述
uj5u.com熱心網友回復:
For回圈不起作用,但是當我這樣嘗試時。
<div>
<p>{{this.bids[0].userName}}</p>
</div>
它的顯示值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529107.html
標籤:html有角度的
