如上所述,变更检测会导致这种行为,它每次都会调用该方法并触发该方法(一个http请求)。
一种可行的方法是在组件初始化时加载图像。 (重要的是,在你的组件中添加一个 *ngIf,否则你的对象可能不会被初始化)
#1 父组件
<ns-bills-cardview *ngIf="billsBook" [billsBook]="billsBook"></ns-bills-cardview>
#2 在您的组件中,只需从缓存或 http 请求中加载图像
export class BillsCardviewComponent implements OnInit {
@Input() billsBook: BillsBook[];
productDocuments: BillBookPrictureData[] = [];
ngOnInit(): void {
this.authService.userTake1Observable.pipe(take(1)).subscribe(user => {
if (user) {
// pre-loading billBook detail images
this.loadingImages();
}
});
}
onLoadImage(productUUID): string {
const picture: BillBookPrictureData = this.productDocuments.find(
productDocument => productDocument.key === productUUID
);
return picture.data;
}
onItemTap(bill: BillsBook, productUUID: string) {
this.billDetailDialogModalService.openBillDetailDialogModal(this.vcRef, this.modal, bill.uuid, productUUID);
}
/**
* This method will get called to re-load all billBook images
*/
private loadingImages() {
this.billsBook.forEach(bill => {
const billUUID = bill.uuid;
bill.products.forEach(product => {
const billBookPicture: BillBookPrictureData = { key: null, data: null };
// cache billPictureData
billBookPicture.key = product.productDocument.uuid;
billBookPicture.data = this.loadImage(billUUID, billBookPicture.key);
this.productDocuments.push(billBookPicture);
});
});
}
/**
* This method will load all images from appSettings or send http request
* @param string billUUID
* @param string productUUID
*/
private loadImage(billUUID: string, productUUID: string): string {
//load billBook images from cache
if (this.appSettingsService.hasBillDetailFileData(billUUID, productUUID)) {
return this.appSettingsService.getBillDetailFileData(billUUID, productUUID);
}
//load billBook images via http request
this.documentControllerService
.getDocumentFileDataUsingGET(productUUID)
.pipe(take(1))
.subscribe(
fileData => {
//store image in cache
this.appSettingsService.setBillDetailFileData(fileData, billUUID, productUUID);
//push loaded image to productDocument array
const billBookPicture: BillBookPrictureData = { key: productUUID, data: fileData };
this.productDocuments.push(billBookPicture);
},
error => console.log(error)
);
}
}
#3 面具
<StackLayout *ngFor="let product of item.products" (tap)="onItemTap(item, product.uuid)">
<Image
*ngIf="productDocuments"
[src]="'data:image/jpeg;base64, ' + onLoadImage(product.productDocument.uuid)"
[alt]="product.name"
width="200"
height="120"
stretch="aspectFill"
></Image>
.
.
.
</StackLayout>
此解决方案可适用于加载一张或多张图片。