簡體   English   中英

如何將 Firebase 雲存儲中返回項目的 URL 推送到 Angular 中的數組中?

[英]How can I push URLs of returned items from Firebase Cloud Storage into an array in Angular?

目標:
目標是使用 listAll() 返回存儲在 Firebase 存儲桶中的圖像,然后使用getDownloadURL() listAll()獲取它們的 URL,並將每個 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
});

我對這一切都很陌生,只是想學習 web 技術,所以請對我輕松一點。 謝謝

看起來問題在於理解“this”在 js 中的工作方式。 正如Mozilla 網站上所述,有兩種方法可以解決您面臨的問題。

首先確定問題:

在大多數情況下, this 的值取決於 function 的調用方式(運行時綁定)。 執行時不能賦值設置,每次調用function時可能不同。

在當前上下文中,您通過定義常規 function 來處理listAll().thenresult.items.forEach來丟失對“this”的引用。

然后看看可能的解決方案:

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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM