【问题标题】:Angular add a random JPG image?Angular添加随机JPG图像?
【发布时间】:2020-02-19 14:59:10
【问题描述】:

我创建了一个 Angular 应用程序,它有一个向列表添加新项目的按钮,这是它的图片:

我搜索了提供随机图片的网站,发现“picsum.photos”(Lorem Picsum),刷新后确实每次都会给我一张随机图片。

我尝试在代码中实现这一点,但每次都得到相同的图像。

TypeScript 代码:

imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}

HTML 代码:

<button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>

似乎只有一个随机图像链接被保存到变量“randomImgUrl”中...

有人知道是什么问题吗?每次调用 addRecipe() 函数时如何获取随机图像?

谢谢!

【问题讨论】:

  • 添加参数更改urlhttps://picsum.photos/536/354?t=123。例如:将 123 替换为当前时间戳。

标签: javascript node.js angular typescript


【解决方案1】:
getRandomImgUrl() {
  return this.randomImgUrl + '?cache=' + new Date().getTime()
}

addRecipe() {
  this.recipes1.push(new Recipes('name', 'description', this.getRandomImgUrl()));
}

【讨论】:

    【解决方案2】:

    在 randomImgUrl 中使用随机数

    addRecipe() {
    this.randomImgUrl=`https://i.picsum.photos/id/${Math.round(Math.random() * 1000)}/535/535.jpg`;
       this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
    }
    

    【讨论】:

      【解决方案3】:

      添加随机查询参数以防止您的浏览器缓存此图像。

      addRecipe() {
        this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl + '?q=' + Math.random()));
      }
      

      【讨论】:

        【解决方案4】:

        您可以通过在末尾附加一个缓存清除查询字符串来更改图像

        randomImgUrl = 'https://picsum.photos/536/354?a';
        

        【讨论】:

        • 查询参数需要以某种方式随机化,否则它只会缓存该版本的图像 url。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-09
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多