在Angular更新图像后,需要调用Angular的“changeDetectorRef.detectChanges()”方法来检测变化并刷新UI。在组件中注入ChangeDetectorRef服务并在图像更新后调用detectChanges()方法即可。
示例代码:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ProductService } from './product.service';
import { Product } from './product';
@Component({
selector: 'app-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.css']
})
export class ProductEditComponent implements OnInit {
product: Product;
imageToUpload: File;
imageUrl: string;
constructor(private productService: ProductService, private changeDetectorRef: ChangeDetectorRef) { }
ngOnInit() {
this.product = this.productService.getProductById(1);
this.imageUrl = this.product.imageUrl;
}
handleImageInput(files: FileList) {
this.imageToUpload = files.item(0);
}
updateProduct() {
if (this.imageToUpload) {
this.productService.uploadImage(this.imageToUpload).subscribe((imageUrl: string) => {
this.product.imageUrl = imageUrl;
this.imageUrl = imageUrl;
this.changeDetectorRef.detectChanges();
});
}
this.productService.updateProduct(this.product).subscribe();
}
}