如何用角度刷新图像

新手上路,请多包涵

我需要刷新像这样加载的图像:

 <img [src]="linkPicture" alt="profile photo" width="150px" height="150px">

在打字稿文件中,我有一个变量 this.linkPicture,我最初存储链接。当我更新图片时不刷新。我再次设置变量….

这是我的打字稿代码的一部分

public linkPicture          : string;

初始设置变量

this.service.GetProfile(id).subscribe(resp => {
        .....
        this.linkPicture = resp.Photo;
        console.log(resp); //this show the photo
    });

当我更新图片时

let dialogRef = this.dialog.open(DialogUploadPhotoComponent, {
        data: {
            patientID: this.ss.getCurrentUserApi().PatientID
        },
        width : "550px",
        });
        dialogRef.afterClosed().subscribe(result => {
            if(result != undefined){
                console.log(result);
                this.linkPicture = result;   //I set the new picture.
            }
        });

原文由 Yoedusvany Hdez 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 282
2 个回答

您可以将时间戳查询附加到图像 URL 以强制浏览器重新加载图像。这不应该对托管图像的服务器产生任何负面影响。

更新模板以调用函数:

 <img [src]="getLinkPicture()" alt="profile photo" width="150px" height="150px">

使用可选的时间戳值计算 URL:

 public getLinkPicture() {
     if(this.timeStamp) {
        return this.linkPicture + '?' + this.timeStamp;
     }
     return this.linkPicture;
}

更改 URL 时。创建一个新的时间戳值。

 public setLinkPicture(url: string) {
     this.linkPicture = url;
     this.timeStamp = (new Date()).getTime();
}

即使 URL 相同,时间戳也会发生变化,这会强制浏览器重新加载图像。

原文由 Reactgular 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以这样试试。至少我解决了喜欢这个

在你的 .ts 文件上

export class MainLayoutComponent implements OnInit {
public isDesktopDevice: boolean = true;
public sidebarBackgroundClass!: string;

public sideBarOpen: boolean = true; // *sidebar is open by default
}

ngOnInit(): void {
if (this.isDesktopDevice) { this.sidebarBackgroundClass = this.getLayoutBackground();
}

public getLayoutBackground(): string {
const bgs: string[] = [
  'side1-1',
  'side1-2',
  'side2-1',
  'side2-2',
];

const max = bgs.length;
const min = 0;
const index = Math.floor(Math.random() * (max - min)) + min;
const bgClass = bgs[index];
return bgClass;

然后像这样将照片一张一张地添加到您的 css 文件中:

.css

 .side1-1{ background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)),url('/assets/images/side/side1.1.jpg') !important;}

最后将类添加到您的 html:

 <mat-drawer [class]="sidebarBackgroundClass"></mat-drawer>

原文由 Emre Koca 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题