簡體   English   中英

console.log()顯示正確的值,但是將其分配給變量時,該值未定義-Angular,firestore

[英]console.log() displays the correct value, but when assigned it to a variable, it is undefined - Angular, firestore

我正在開發Angular應用程序,並希望從Firestore獲取一些數據。 但是我的函數總是返回undefined 但是,當我在返回值之前console.log()該值時,它將顯示正確的值。

getToken(user_id) {
    this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token; //returns undefined!
      }
    });
}

兩個值不應該相同嗎?

似乎您沒有從函數中返回Promise - getToken函數中根本沒有return語句,因此該函數本身僅返回undefined 您擁有的內部return語句將解決諾言,這很好,但是您必須處理該決議。

如果您像這樣返回承諾:

getToken(user_id) {
    return this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token;
      }
    });
}

通過以下承諾,您應該能夠異步訪問user_token

getToken(user_id).then(user_token => {
  handle_user_token_here(user_token);
});

注意 :修改后的函數將返回promise。 因此,您不能簡單地執行以下操作:

let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
handle_user_token_here(user_token); // will not work.

您可以這樣做:

let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
user_token.then(user_token => handle_user_token_here(user_token)); // will work

這可能會回答您的問題: 即使存在對象屬性也無法訪問。 返回未定義

“ console.log(anObject)的輸出具有誤導性;僅當您在控制台中展開>時,才能解決所顯示對象的狀態。”

換句話說,doc.data()。user_token可能會被異步進程填充。

暫無
暫無

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

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