![](/img/trans.png)
[英]Firebase TypeError: Cannot read properties of null (reading 'indexOf')
[英]EDIT - Firebase Timestamp Causing 'Cannot read properties of null' error in HTML interpolation while adding new document
session.startDate 是一個 firebase 時間戳,我正在使用 toDate() function 和我的 HTML 中的日期 pipe 轉換它。這非常有效,直到我開始通過服務添加文檔。
{{session.startDate.toDate() | date}}
添加新文檔后,雖然所有內容都可以在屏幕上正確呈現,但我收到了大量憤怒的控制台消息:
ERROR TypeError: Cannot read properties of null (reading 'toDate')
因此,我猜測當服務添加文檔時,在填充 startDate 之前有足夠的時間 the.toDate() function 在數據存在之前失敗。
我確定我要做的事情非常簡單,我只是不確定我應該在我的項目中的什么時候等待數據,以及最好的方法。
為此,我使用了 2 個組件:顯示組件和服務組件。
顯示組件當顯示首次加載時,我獲取當前路由 ID,並將 sessionSource 設置為訂閱的 sessionService。
ngOnInit(): void {
this.subscribe = this.activatedRoute.paramMap.subscribe(params => {
this.pid = params.get('pid');
})
this.sessionService.getSessionList(this.pid).subscribe((value) => {
this.sessionSource = value
});
}
然后在 HTML 中,我運行 *ngFor 以顯示不同文檔的列表。
<mat-expansion-panel *ngFor=" let session of sessionSource"
<mat-expansion-panel-header>
<mat-panel-title>
{{session.startDate.toDate() | date}}
</mat-panel-title>
<mat-panel-description>
{{session.sessionDescription}}<div *ngIf="session.active"> - Active Session</div>
</mat-panel-description>
</mat-expansion-panel-header>
</mat-expansion-panel>
Session 服務當我使用我的服務添加一個新的 session 時,這就是正在運行的服務(請注意,有一些正在進行的“返回”功能可以將新創建的文檔 ID 取回用於我尚未開始工作的路由)。
這成功地添加了一個新條目,並按預期顯示在頁面上,但出現了上述錯誤。
startNewSession(pid: string){
return this.afs.collection("/Management/"+pid+"/Sessions").add({
active: true,
startDate: firebase.firestore.FieldValue.serverTimestamp(),
sessionDescription: 'Testing Adding'
}).then(docRef => {
return docRef.id
}).catch(error => console.error("Error adding document: ", error))
}
好吧,解決方案非常簡單,但我花了一段時間才弄清楚問題出在哪里。 最后,我回到了我第一次在medium上使用 firebase 時間戳時讀過的一篇文章。 有很多細節,但結果是,在時間戳最終確定之前,它將默認返回 null 值,這就是導致我的 null 錯誤的原因。
解決方案是使用“ SnapshotOptions ”來修改每個文檔快照,並估計時間戳是多少。 我不需要納秒精度,所以這非常適合我的使用。
最后,我的更改甚至不在我最初發布的內容中,它在服務內部,並且是在 ngOnIt 中返回對 sessionSource 的訂閱的內容。
下面是整個部分,但我所做的只是添加 { serverTimestamps: 'estimate' } 作為 payload.doc.data() function 的選項。這組是估計的時間戳,我不再有 null 錯誤。
getSessionList(pid: string){
return this.afs.collection(this.CollectionPath+pid+'/Sessions', ref => ref.orderBy('startDate', 'desc')).snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data({ serverTimestamps: 'estimate' }) as sessions_list;
const id = a.payload.doc.id;
return { id, ...data };
})
}
))
}
我在尋找解決方案時發現了一個類似的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.