我想從名為 Events 的 Firestore 集合中獲取我擁有的 eventID 的值。我能夠在我的應用程式中獲取并顯示我的 firestore 集合中的所有事件,但我需要它eventID來完成其他功能。
我是 TS 和 Angular 的新手,不明白為什么這不起作用
當我userid在 auth 函式內記錄我的變數時,它作業正常并檢索值,但如果我在函式外這樣做,它會給出未定義。
此外,當我記錄eventList我為存盤來自 firestore 的資訊而創建的整個變數時,它會記錄所有資訊,但例如,如果我嘗試檢索任何內容,this.eventList.eventID或者this.eventList.title它會記錄未定義的資訊。
我究竟做錯了什么?
這是我的代碼:
import { Component,OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
import { async } from '@firebase/util';
export class Tab1Page implements OnInit {
public eventList;
public userid;
constructor(private firestore: AngularFirestore, public fAuth: AuthService, public router: Router) {}
ngOnInit(){
this.fAuth.firebaseAuth.user.subscribe(res => {
this.userid = res.uid; //current logged in user id
//fetch only events logged in user created
this.firestore.collection('Events',ref=>ref.where("eventCreator","==",this.userid)).valueChanges().subscribe(event => {
this.eventList = event
console.log(this.eventList)//logs all the info from firestore
console.log(this.eventList.eventID)//logs undefined
console.log(this.userid)//logs the userid
});
});
console.log(this.userid)//logs undefined
}
}
uj5u.com熱心網友回復:
作為 console.log(this.userid) // logs undefined
作為@MikeOne參考內部的函式subscribe是異步的。這些函式通常會在稍后執行。所以在 console.log(this.userid)//logs undefined執行的時候,this.userid = res.uid;仍然沒有被執行。
作為 console.log(this.eventList.eventID) // logs undefined
我猜this.eventList是陣列。嘗試this.eventList[0].eventID等等來訪問每個元素。
uj5u.com熱心網友回復:
要解決undefined嵌套訂閱發生的資料回應問題,請使用 RxJSswitchMap()運算子將外部 observable 的結果從fAuth.firebaseAuth.userobservable傳遞到內部 observable,即this.firestore.collection..observable,從那里您可以從流中分配事件串列一個訂閱中所有內部可觀察物件的回應:
像這樣(我不確定您的事件資料的結構 - 它是一個陣列或一個類/介面,它是一個包含陣列的標頭,所以我將 anany作為回應型別):
this.fAuth.firebaseAuth.user
.pipe(
switchMap((res: any) => {
this.userid = res.uid; //current logged in user id
//fetch only events logged in user created
const eventListObservable: Observable<any> =
this.firestore.collection('Events',ref =>
ref.where("eventCreator","==",res.uid))
.valueChanges()
.pipe(
map((event: any) =>
{
this.eventList = event;
console.log(event); //logs all the info from firestore
console.log(event.eventid); //logs event id
console.log(user.id); //logs the userid
return event;
})
);
return eventListObservable;
})
)
.subscribe();
作為最佳實踐,您可以將上述內容分配給 asubscription并稍后在ngDestroy()處理程式中將其釋放。
要試驗和測驗上述嵌套的 observable,首先使用簡單的模擬服務,然后將您的 observable 附加到實時服務。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362676.html
標籤:有角的 打字稿 火力基地 离子框架 谷歌云firestore
上一篇:將值傳遞給另一個組件
下一篇:使用.net登錄/注冊
