在 Angular 4 中,清理后的图像 URL 仍然被请求的问题可能是由浏览器缓存导致的。以下是一种解决方法:
import { Component } from '@angular/core';
@Component({
selector: 'app-image',
template: `
`
})
export class ImageComponent {
imageUrl = 'https://example.com/image.jpg';
getImageUrl() {
const randomParam = Math.random().toString(36).substring(7);
return this.imageUrl + '?rand=' + randomParam;
}
}
在上面的示例中,将一个随机参数(?rand=
)添加到图像 URL 的末尾。每次调用 getImageUrl()
方法时,将生成不同的随机参数,这样浏览器就会认为它是一个新的 URL,并发送请求获取新的图像。
import { Component } from '@angular/core';
@Component({
selector: 'app-image',
template: `
`
})
export class ImageComponent {
imageUrl = 'https://example.com/image.jpg';
version = '1.0'; // 或者使用时间戳
getImageUrl() {
return this.imageUrl + '?v=' + this.version;
}
}
在上面的示例中,将一个版本号参数(?v=
)添加到图像 URL 的末尾。当图像文件更改时,只需更新版本号,浏览器就会强制获取新的图像。
通过以上两种方法,可以确保每次请求的图像都是新的,而不是从浏览器缓存中获取的。