我對 Angular 還很陌生,并且一直在努力解決 Firebase 的某些方面問題。我正在嘗試檢索集合中的最新檔案以獲取最后一個檔案的 ID 并使用該 ID(添加 1)來創建新檔案。我有一個 CRUD 服務檔案,其中包含:
import Pedido from './interfaces';
import { AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import * as moment from 'moment';
@Injectable({
providedIn: 'root'
})
export class CrudFirestoreService {
productRef: AngularFirestoreCollection<Producto_interface>;
private dbPedidosPath = '/Pedidos';
constructor(private store: AngularFirestore, private router: Router, private dialog: MatDialog) {
this.pedidosRef = store.collection(this.dbPedidosPath);
}
getLastPedido(): AngularFirestoreCollection<Pedido>{
return this.store.collection(this.dbPedidosPath, ref => ref.orderBy('Fecha', 'desc').limit(1))
}
以前,我用 snapshotChanges 呼叫這個參考:
this.crud.getLastPedido().snapshotChanges()
.pipe(map(changes => changes.map(c =>({cod: c.payload.doc.id, ...c.payload.doc.data() }))))
.subscribe(data => { CALLBACK }
但是我遇到了它被多次呼叫的問題,即使資料庫沒有改變。由于我使用函式回呼來繼續該程序,這意味著該程序被多次啟動。
this.crud.getLastPedido().get().subscribe(data => {
console.log("data",data)
console.log("data[0]", data[0])
CALLBACK }
但是,當我嘗試這樣做時,它最終回傳一個空物件:
Object { _firestore: {…}, _delegate: {…} }
?
_delegate: Object { _firestore: {…}, _userDataWriter: {…}, _snapshot: {…}, … }
??
_firestore: Object { type: "firestore", _persistenceKey: "angular-auth-firebase", _settingsFrozen: true, … }
??
_snapshot: Object { fromCache: false, syncStateChanged: true, excludesMetadataChanges: false, … }
??
_userDataWriter: Object { firestore: {…} }
??
metadata: Object { hasPendingWrites: false, fromCache: false }
??
query: Object { converter: null, _query: {…}, type: "query", … }
??
<prototype>: Object { … }
?
_firestore: Object { _delegate: {…}, _persistenceProvider: {}, INTERNAL: {…}, … }
?etc.
從本質上講,我要么需要一種更好的方法來運行我的異步函式,以便我可以使用 snapshotChanges 并忽略回呼函式被呼叫的可變次數,要么我需要弄清楚為什么不能像這樣回傳單個檔案在職的。
謝謝!
uj5u.com熱心網友回復:
代替
this.crud.getLastPedido().get().subscribe(data => {
console.log("data",data)
console.log("data[0]", data[0])
CALLBACK }
嘗試
this.crud.getLastPedido().get()
.pipe(
map(res => res.docs.map((snap) => {
return {
id: snap.id,
...snap.data()
}))
)
.subscribe(data => {
console.log("data",data)
)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496538.html
