如何访问我的代码中的重定向 URL?,javascript,html,angular,typescript"/>

首页 > 解决方案 > Angular如何访问我的代码中的重定向 URL?

问题描述

在 Angular 应用程序中,我将图像 src 设置为自定义 URL,例如,https://source.unsplash.com/1600x900/?facebook这会被重定向到托管在其服务器上的某个图像。

在某些情况下,结果 URL 将重定向到错误的图像,例如,https://source.unsplash.com/1600x900/?roblox将重定向到https://images.unsplash.com/source-404?fit=crop&fm=jpg&h=800&q=60&w=1200每次没有好的结果时的术语(即 roblox,在这种情况下,是一个不好的术语)。

如何在我的代码中访问此重定向 URL?

我已经尝试过的:

我将 HTMLInputElement 通过<img [src]="someFunctionReturningURL(t)" #t>. 在内部someFunctionReturningURL(t),我调用 a setTimeout(以确保img已完全加载srcURL)并测试t.src == "https://images.unsplash.com/source-404?fit=crop&fm=jpg&h=800&q=60&w=1200"问题是否t.src仍然存在原始未重定向链接https://source.unsplash.com/1600x900/?roblox,而不是它实际重定向到的链接!

标签: javascripthtmlangulartypescript

解决方案


您可以使用 fetch 方法获取重定向的 url,然后在 src 属性上设置它:

fetch("https://source.unsplash.com/1600x900/?facebook")
  .then(res => {
    if (res.url) {
      this.imageSrc = res.url;
      console.log(this.imageSrc);
    }
  });

代码沙盒示例


推荐阅读