以前使用实时数据库,我已经习惯于使用订阅来监视数据库中的更改。但是,Cloud Firestore具有.valueChanges()似乎可以自动执行此操作,所以我仍然需要使用rxjs订阅吗?
我的代码无法正常工作,没有问题,我询问的是_subscription: Subscription;
而不是.valueChanges().subscribe
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
import 'firebase/database';
import 'rxjs/Rx';
import { Observable, pipe, of, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class FirebaseService {
_data: any = [];
_subscription: Subscription;
itemsDocument_data: AngularFirestoreDocument<any[]>;
itemsCollection_data: AngularFirestoreCollection<any[]>;
constructor(private _afDB: AngularFirestore) {
await _dbGeData();
}
private async _dbGeData() {
try {
if (this._fbData_subscription_User === undefined) {
this.itemsDocument_users = this._afDB.collection("_myDataPath").doc("_mySecondDatapath");
this._subscription_data = await this.itemsDocument_data.valueChanges().subscribe((items) => {
this._data = [];
for (let i in items) {
this._data.push = items[i];
}
//items (object) is now this._data (Array)
console.log("items (object)", items);
console.log("this._data (Array)", this._data);
return;
});
}
} catch (e) {
console.error("when getting data", e);
return;
}
return;
}
ngOnDestroy() {
if (this._subscription !== undefined) {
this._subscription.unsubscribe();
}
}
}
答案 0 :(得分:0)
valueChanges()
返回一个可观察的对象,您必须以一种或另一种方式订阅它才能实际发生任何事情。
您难道不能停留在此可观察范围内并在最后一刻订阅吗(例如在带有AyncPipe
的模板中)?