如何在Angular中把Firebase云存储中返回的项目的URL推送到一个数组中?

问题描述 投票:0回答:1

目标。 我们的目标是使用Firebase云存储桶返回存储在Firebase云存储桶中的图片。listAll() 然后用 getDownloadURL() 并将每个URL推送到一个数组,用来在图库中显示图片。

问题是 我成功地返回了URLs,但是当我试图将它们推送到一个空数组时,我得到了这个错误。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
});

我对这些都很陌生,只是想学习网络技术,所以请对我好一点,谢谢。

javascript angular typescript firebase ionic-framework
1个回答
1
投票

看来问题出在对js中 "this "如何工作的理解上。莫斯拉网站 有两种方法可以解决你所面临的问题。

首先要确定问题所在。

在大多数情况下,这个值是由函数的调用方式决定的(运行时绑定)。它不能在执行过程中通过赋值来设置,而且每次调用函数时可能都不同。

在当前的上下文中,你通过定义一个常规函数来处理你想要的'this'的引用,就失去了 listAll().thenresult.items.forEach.

然后看看可能的解决方案。

ES5引入了bind()方法来设置一个函数的this值,而不管它是如何被调用的;ES2015引入了箭头函数,它不提供自己的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
});
© www.soinside.com 2019 - 2024. All rights reserved.