我刚接触angularfire 2并遇到问题。我有一套餐厅存放在firebase的cloudflare中。我能够正确获取餐馆列表并显示它,但是当我尝试访问并将特定餐馆保存到单独的变量时,它会返回一个我无法从中获取数据的可观察对象:
items: Observable<any[]>;
tester: any[] = [];
private test: AngularFirestoreCollection<any>;
constructor(db: AngularFirestore){
this.test = db.collection<any>('restaurants')
// this.items = db.collection('restaurants').valueChanges();
this.items = this.test.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
this.tester.push(data); //This returns an observable instead of an array
const id = a.payload.doc.id;
return { id, ...data };
});
});
}
getRestaurants(){
return this.items;
}
//Here I want to be able to return the item object
getRestaurant(index){
console.log(this.tester[i]);
}
组件代码
constructor(private restService: RestaurantService){}
restaurants = <any>[];
selectedRestaurant: any;
ngOnInit(){
this.restaurants = this.restService.getRestaurants()
}
onSelect(index){
console.log(this.restService.getRestaurant(index));
}
我很难理解如何从firebase返回的Observable列表中提取数据。
答案 0 :(得分:0)
如果你想获得&#34;当前值&#34;对于Observable,您应该使用BehaviorSubject。
restaurants: BehaviorSubject<any[]>;
private test: AngularFirestoreCollection<any>;
constructor(db: AngularFirestore){
this.test = db.collection<any>('restaurants')
this.test.snapshotChanges().subscribe(this.restaurants);
}
getRestaurants(){
return this.restaurants.value();
}
getRestaurant(index){
return getRestaurants()[index]; //.. or whatever you need
}