【问题标题】:angularfire2 snapshot dataangularfire2 快照数据
【发布时间】:2017-12-12 07:57:43
【问题描述】:

我是 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 列表中提取数据。

【问题讨论】:

  • 你需要使用snapshot()吗?因为 valuechanges() 更容易使用。我可以举个例子

标签: angular firebase angularfire2


【解决方案1】:

如果你想获得 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多