2017-10-05 43 views
0

angularfire2 docs中,它解釋了爲了保留與.valueChanges()一起使用的文檔ID,應該使用afs.createId()創建一個。在.valueChanges()中使用的持久文檔ID提供了兩個不同的ID

export class AppComponent { 
    private itemsCollection: AngularFirestoreCollection<Item>; 
    items: Observable<Item[]>; 
    constructor(private readonly afs: AngularFirestore) { 
    this.itemsCollection = afs.collection<Item>('items'); 
    // .valueChanges() is simple. It just returns the 
    // JSON data without metadata. If you need the 
    // doc.id() in the value you must persist it your self 
    // or use .snapshotChanges() instead. See the addItem() 
    // method below for how to persist the id with 
    // valueChanges() 
    this.items = this.itemsCollection.valueChanges(); 
    } 
    addItem(name: string) { 
    // Persist a document id 
    const id = this.afs.createId(); 
    const item: Item = { id, name }; 
    this.itemsCollection.add(item); 
    } 
} 

但是,當添加到集合中時,項目的ID和存儲在其中的項不同。它是否正確?添加到集合時是否有設置密鑰的方法,以便它們匹配?我覺得有兩個ID可能會在未來頭痛。

我知道.snapshotChanges()提供了元數據,但是我正在流式傳輸項目中的項目,並且映射快照更改會導致每個條目以角度重新呈現。我覺得這是個什麼文件警告,當他們說以下內容:

snapshotChanges()

...

當你不使用它呢? - 當您需要比數組更復雜的數據結構時,或者需要在發生更改時處理更改。

+0

我結束了使用snapshotChanges()在我的收藏,列出了一堆的項目來獲得ID。當你說它導致每個條目重新呈現時,到底發生了什麼?我想我在使用snapshotChanges()和AngularFirestoreDocument時遇到了這個問題,但無法找出原因。 – MegaTron

+0

我的問題是這樣的:每個項目都有一個子集合。當一個項目在一個ItemComponent中呈現時,它將獲取一個子集合。當一個新項目被添加到列表中時,它會重新獲取每個項目的子集合。我檢查了它,並且每次添加時都會重新初始化每個項目的組件。在我看來,它只會爲新添加的項目添加一個新組件。我可能會在這裏做一個基本的錯誤,這不是特定於angularfire2 ... –

+0

@MegaTron我設法解決我的問題與trackBy在* ngFor([文檔](https://angular-2-training-book.rangle.io /handout/directives/ng_for_directive.html))。它可以防止在我的項目數組更新時重新初始化我的組件,也可以在那裏找到針對您的問題的答案。 –

回答

0

我不知道爲什麼文檔說明了,如果有人能給出解釋我會很感激。

我解決了這個問題如下創建文檔時明確設置ID:

public addSubBudget = (bdgtId, description: string) => { 
    const coord = BUDGET_COLLECTION + '/' + bdgtId + '/sub-budgets'; 
    const subBudgetCollRef = this.afs.collection<SubBudget>(coord); 
    const id = this.afs.createId(); 
    const subBudget: SubBudget = { id, description }; 
    return subBudgetCollRef.doc(id).set(subBudget); 
} 
相關問題