首页 > 解决方案 > 如何将 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
});

我对这一切都很陌生,只是想学习网络技术,所以请放轻松。谢谢

标签: javascriptangulartypescriptionic-frameworkfirebase-storage

解决方案


看起来问题在于理解“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
});

推荐阅读