javascript - 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
已完全加载src
URL)并测试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
,而不是它实际重定向到的链接!
解决方案
您可以使用 fetch 方法获取重定向的 url,然后在 src 属性上设置它:
fetch("https://source.unsplash.com/1600x900/?facebook")
.then(res => {
if (res.url) {
this.imageSrc = res.url;
console.log(this.imageSrc);
}
});
推荐阅读
- c# - .NET Core 2.2:如何将 WSDL 用于 WCF 参考
- ubuntu - 如何在 ubuntu 中访问我的 USB 键盘固件?
- assembly - 为什么这个汇编语言程序无法在 Windows 7 或 DOSBox 下运行?
- mongodb - Mongo:使用 .find({_id: id}) 与 .findOne({_id: id}) 是否相同?
- java - OpenMath-Objects 可以在相等性方面与另一个进行比较吗?
- javascript - 如何在 R 闪亮中动态移动 UI 元素(主要是 mainPanel)?
- javascript - 如何仅在单击确定按钮后才使元素 UI 时间选择器设置值?
- c++ - 对包含数字和单词的字符串向量进行排序
- php - 正则表达式 301 重定向不起作用
- php - PHP 表单/准备好的语句错误