如何使用 snapshotChanges() 方法获取键值并过滤数据? [英] How to use snapshotChanges() method to get both key value and filter the data?

查看:15
本文介绍了如何使用 snapshotChanges() 方法获取键值并过滤数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个 Angular Firebase 项目,我需要在其中过滤我的数据库并获取键值.目前,我在我的服务代码中使用 valueChanges() 方法(在 getUnreadBooks 和 getFavoriteBooks 方法中,如下所示)来获取数据并对其进行过滤.但是当我尝试在模板文件中获取键值时,它给我的键值为未定义".我尝试使用 snapshotChanges() 方法,但无法解决如何使用它来获取关键值以及过滤数据.下面分别是我的 Angular FirebaseService、home.component.ts(我在其中注入了我的服务代码)和 home.component.html(模板文件)代码:

I'm working on an Angular Firebase Project, where I need to filter my database as well get the key values. Currently I'm using valueChanges() method in my service code (inside getUnreadBooks and getFavoriteBooks methods, as shown below) to get the data and filter it. But it gives me key value as 'undefined', when I try to get key value inside my template file. I tried to go with snapshotChanges() method, but can't work around how to use it to get key values along with filtering the data . Below are my Angular FirebaseService, home.component.ts (in which I am injecting my service code) and home.component.html (template file) Code respectively:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class FirebaseService {

  books: Observable<any[]>;
  unreadBooks;
  favoriteBooks;

  constructor(private db: AngularFireDatabase) {}

  getBooks(){
        this.books = this.db.list('/books').valueChanges() as Observable<any[]>;
        return this.books;
    }       

  getFavoriteBooks(){
    this.favoriteBooks = this.db.list('/books').valueChanges() as Observable<any[]>;
    this.favoriteBooks = this.favoriteBooks.map(books => {
        const topRatedBooks = books.filter(item =>  item.rate>4);
        return topRatedBooks;
    })
    return this.favoriteBooks;
  }

  getUnreadBooks(){
    this.unreadBooks = this.db.list('/books').valueChanges() as Observable<any[]>;
    this.unreadBooks = this.unreadBooks.map(books => {
        const ub = books.filter(item => item.dateread == null);
        return ub;
    })
    return this.unreadBooks;
  }
}

Home.Component.ts 文件 =>

Home.Component.ts file =>

import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../services/firebase.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  //favorite Books
  favoriteBooks: any;
  unreadBooks: any;

  constructor(private firebaseService: FirebaseService) { }

  ngOnInit() {
    this.firebaseService.getFavoriteBooks()
        .subscribe(favBooks => {
            this.favoriteBooks = favBooks;
            console.log(this.favoriteBooks);
        })
    this.firebaseService.getUnreadBooks()
        .subscribe(ubBooks => {
            this.unreadBooks = ubBooks;
            console.log('Unread Books:', this.unreadBooks);
        })
  }

}

Home.component.html 文件 =>

Home.component.html file =>

<mat-toolbar>
    My Top Rated Books
</mat-toolbar>
<mat-grid-list cols="3">
    <mat-grid-tile *ngFor="let book of favoriteBooks">
        <mat-card>
            <mat-card-header>
                <mat-card-title>
                    <h4>{{book.title}}</h4>
                </mat-card-title>
            </mat-card-header>
            <img mat-card-image src="{{book.imageUrl}}" alt="{{book.title}}">
            <mat-card-actions>
                <button mat-button mat-raised-button class="detailsButton" [routerLink]="['/book/'+book.$key]">
                    <i class="material-icons">visibility</i>Book Details</button>
                <button mat-button mat-raised-button class="editButton" [routerLink]="['/editbook/'+book.$key]">
                    <i class="material-icons">mode_edit</i>Edit Book</button>
            </mat-card-actions>
        </mat-card>     
    </mat-grid-tile>
</mat-grid-list>

<mat-toolbar>
    Books I have not read yet
</mat-toolbar>
<mat-grid-list cols="3">
    <mat-grid-tile *ngFor="let book of unreadBooks">
        <mat-card>
            <mat-card-header>
                <mat-card-title>
                    <h4>{{book.title}}</h4>
                </mat-card-title>
            </mat-card-header>
            <img mat-card-image src="{{book.imageUrl}}" alt="{{book.title}}">
            <mat-card-actions>
                <button mat-button mat-raised-button class="detailsButton" [routerLink]="['/book/'+book.$key]">
                    <i class="material-icons">visibility</i>Book Details</button>
                <button mat-button mat-raised-button class="editButton" [routerLink]="['/editbook/'+book.$key]">
                    <i class="material-icons">mode_edit</i>Edit Book</button>
            </mat-card-actions>
        </mat-card>     
    </mat-grid-tile>
</mat-grid-list>

推荐答案

声明一个将 id 添加到对象的函数:

Declare a function to add id to your Object :

documentToDomainObject = _ => {
    const object = _.payload.doc.data();
    object.id = _.payload.doc.id;
    return object;
}

并在您的 getBooks 方法中使用它:

And use it in your getBooks method :

getBooks(){
  this.books = this.db.list('/books').snapshotChanges()
  .pipe(map(actions => actions.map(this.documentToDomainObject)));

  return this.books;
}

这篇关于如何使用 snapshotChanges() 方法获取键值并过滤数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆