慕碼人2483693
2022-09-29 16:39:42
有很多消防商店集合獲取實時更新的文檔和示例。但是,對于那些希望單個文檔進(jìn)行實時更新的人來說,幾乎沒有什么。我想在一個頁面上有一個文檔(一個),只有頁面將被查看和操作,并且對文檔的任何更改,都會有實時更新。itemitem這是我的組件,想要用做一些事情:itemimport { Component, OnInit } from '@angular/core';import { ItemsService } from '../shared/items.service';import { ActivatedRoute, Router } from '@angular/router';@Component({ selector: 'app-view-item', templateUrl: './view-item.component.html', styleUrls: ['./view-item.component.css']})export class ViewItem implements OnInit { item; private sub: any; constructor( // Service used for Firebase calls private itemsService: ItemsService, private route: ActivatedRoute, private router: Router ) {} ngOnInit() { // Item retrieved from */item/:id url this.sub = this.route.params.subscribe(params => { this.getItem(params['id']); }); } getItem = (id) => { this.itemsService.getItem(id).subscribe(res => { console.log(res); this.item = res; console.log(this.item); }); }我得到的日志是 。在控制臺中調(diào)用將返回相同的結(jié)果。我不確定如何繼續(xù),并希望得到任何指導(dǎo)。在控制臺中登錄將返回一個拜占庭對象。也許這就是我訪問的方式,但如果是這樣,為什么它沒有保存,我如何訪問 的值?console.log(this.item)undefinedthis.itemresitemthis.itemitem
1 回答

智慧大石
TA貢獻(xiàn)1946條經(jīng)驗 獲得超3個贊
snapshotChanges返回可觀察的操作,而不是實際值。應(yīng)使用 提取值:action.payload.doc.data()
因此,您的代碼應(yīng)類似于以下示例。
getItem(id) {
return this.firestore.collection('items').doc(id).snapshotChanges()
.pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
})
);
}
或者您可以使用 .valueChangesdoc
getItem(id) {
return this.firestore.collection('items').doc(id).valueChanges();
}
添加回答
舉報
0/150
提交
取消