javascript - 如何将 Firebase Cloud Storage 中返回项目的 URL 推送到 Angular 中的数组中?
问题描述
目标:
目标是返回存储在 Firebase 存储桶中的图像,listAll()
然后使用它们获取它们的 URL getDownloadURL()
,并将每个 URL 推送到一个数组,该数组将用于在图库中显示图像。
问题:
我成功返回了 URL,但我收到了这个错误:TypeError: "_this is undefined"
当我尝试将它们推送到一个空数组时。
我做了什么:
在过去的 3 天里,我尝试了几种方法,这是我能想到的最好的方法:
声明一个空数组:
export class imgService {
public images = []
方法:
//creating a reference
var itemsRef = firebase.storage().ref().child('images/');
// listing the images
itemsRef.listAll().then(function (result) {
result.items.forEach(function (itemRef) {
// getting the URLs of the images
itemRef.getDownloadURL().then(downloadURL => {
console.log('URL:' + downloadURL);
// pushing URLs to the empty images array
this.images.push(downloadURL); //PROBLEM OCCURS HERE
}).catch(function (error) {
//Handling error here
});
});
}).catch(function (error) {
//Handling error here
});
我对这一切都很陌生,只是想学习网络技术,所以请放轻松。谢谢
解决方案
看起来问题在于理解“this”在 js 中的工作方式。正如Mozilla 网站上所述,有两种方法可以解决您面临的问题。
首先确定问题:
在大多数情况下, this 的值取决于函数的调用方式(运行时绑定)。执行时不能通过赋值来设置,每次调用函数时可能都不一样。
在当前上下文中,您通过定义一个常规函数来处理listAll().then
和失去对“this”的引用result.items.forEach
。
然后看看可能的解决方案:
ES5 引入了 bind() 方法来设置函数的 this 的值,而不管它是如何被调用的,ES2015 引入了不提供自己的 this 绑定的箭头函数(它保留了封闭词法上下文的 this 值)。
因此,我们可以明确地绑定到您的意思的“this”,或者使用箭头函数将其全部向下传递。在这种情况下,我个人偏好使用箭头符号,因此以下代码应该可以工作。
希望这可以解决您的问题并帮助您了解潜在的问题。
//creating a reference
var itemsRef = firebase.storage().ref().child('images/');
// listing the images
itemsRef.listAll().then((result) => {
result.items.forEach((itemRef) => {
// getting the URLs of the images
itemRef.getDownloadURL().then(downloadURL => {
console.log('URL:' + downloadURL);
// pushing URLs to the empty images array
this.images.push(downloadURL); //PROBLEM OCCURS HERE
}).catch(function (error) {
//Handling error here
});
});
}).catch(function (error) {
//Handling error here
});
推荐阅读
- java - Whitelabel 错误页面 Spring boot 和 AWS RDS
- c++ - 2d+ 向量会导致性能下降吗?
- asp.net-core - 如何在 IIS 8.5 上解决 .Net Core 2.1.1 上的内部服务器错误 500
- excel - 如果单元格包含值 VBA,则无法删除单元格
- math - 看起来随机的可逆数学函数
- c# - 如何在 Visual Studio 2017 中关闭 Windows 窗体继承?
- ruby-on-rails - 如何访问哈希数据 - Ruby on rails
- python - cpython-35m-x86_64-linux-gnu.so 是从哪个基本文件类型生成的
- javascript - 通过 ajax 向 API 输入多个数据
- css - 溢出-y:滚动;不在桌子上工作