angular - Observable 导航返回后不会返回值
问题描述
我有一个我正在订阅的 observable。它工作正常,但是一旦导航然后再次返回,将不会显示任何数据。怎么会这样?
export class ProductOverviewComponent implements OnInit, OnDestroy {
products;
subscription;
constructor(private data: CollectionService) { }
ngOnInit(): void {
this.subscription = this.data.products.subscribe(value => {
console.log(value);
this.products = value;
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
export class CollectionService {
private productCollection: AngularFirestoreCollectionGroup<any>;
products: Observable<any[]>;
constructor(private db: AngularFirestore) {
this.productCollection = db.collectionGroup('products');
this.fetchProducts();
}
fetchProducts() {
this.products = this.productCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
}))
);
}
}
解决方案
您需要添加一个shareReplay
,以便在订阅之间共享和重播数据:
fetchProducts() {
this.products = this.productCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
})),
shareReplay(1),
// if you want to unsubscribe from source obs when there are no more subscribers
// shareReplay({ refCount: true, bufferSize: 1 })
);
}
推荐阅读
- python - 使用 Python 模糊匹配同一数据框中的两列
- r - 使用 R data.table 从包含向量元素的列中进行选择
- android - Android 通知生成器问题将远程输入添加到操作
- javascript - 仅当画布在滚动后可见时才开始动画 (Animate CC)。
- excel - 在 VBA 中将工作表作为变量从一个子过程传递到另一个子过程
- mysql - MySQL 3 表交叉/左连接优化
- excel - VBA 类模块:主控 3 个不同模块的 25 个复选框和文本框
- react-native - 发送一个完整的反应原生项目,包括所有文件并准备构建
- laravel - 从 laravel 中的两个独立模型获取数据
- python - Sklearn混淆矩阵只显示真阳性和假阳性