【发布时间】:2018-12-22 22:15:51
【问题描述】:
我正在 Angular 上制作我的第一个应用程序。我试图按性别属性过滤书籍对象列表。我在组件之间共享数据时遇到困难:filteredData 变量和书籍列表FireBaseList。
我正在尝试将filteredData 变量从fixed-nav.component 传递给books-grid.component。根据我的研究,我知道我需要使 books-grid.component "bookList" 可观察到任何更改,并让 fixed-nav.component.ts 上的 bookList 在 this.bookList 上的任何更改上发出事件
但是,我无法做到这一点。我知道已经有很多关于 observables 的问题,但没有一个使用 Firebase。希望有大神能帮帮我,谢谢!!
我用作过滤器的fixed-nav.component
import { Component, OnInit } from '@angular/core';
import { BookService } from '../../../services/book.service';
import { Book } from '../../../models/book';
@Component({
selector: 'fixed-nav',
templateUrl: './fixed-nav.component.html',
styleUrls: ['./fixed-nav.component.css']
})
export class FixedNavComponent implements OnInit {
Genders: string[];
bookList: Book[];
constructor(private bookService: BookService) {
this.Genders = ["Historia","Literatura", "Infantil", "Juvenil","Poesía","Narrativa"];
}
filterByGender(gender: string){
this.bookService.getBooks() // FIREBASE
.snapshotChanges()
.subscribe(item => {
this.bookList = [];
item.forEach(element => {
let x = element.payload.toJSON();
x["$key"] = element.key;
this.bookList.push(x as Book)
})
const filteredData = this.bookList.filter( function(element){
return element.gender == gender;
});
return filteredData; // I WANT TO SHARE THIS DATA
})
}
ngOnInit() {
}
}
books-grid.component.ts
import { Component, OnInit } from '@angular/core';
import { BookService } from '../../services/book.service';
import { Book } from '../../models/book';
@Component({
templateUrl: './books-grid.component.html',
styleUrls: ['./books-grid.component.css']
})
export class BooksGridComponent implements OnInit {
bookList: Book[];
constructor(private bookService: BookService) {}
ngOnInit() {
this.bookService.getBooks() // FIREBASE
.snapshotChanges()
.subscribe(item => {
this.bookList = [];
item.forEach(element => {
let x = element.payload.toJSON();
x["$key"] = element.key;
this.bookList.push(x as Book)
})
// SHARED DATA HERE
})
}
}
book.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Book } from '../models/book'; // Model
@Injectable({
providedIn: 'root'
})
export class BookService {
bookList: AngularFireList<any>;
selectedBook: Book = new Book(); // Temporally save selected Book
constructor(private firebase: AngularFireDatabase) { }
getBooks(){
return this.bookList = this.firebase.list('books');
}
}
books.model.ts
export class Book {
$key: string;
title: string;
author: string;
gender: string;
language: string;
image: string;
likes: number;
price: number;
new: boolean;
}
【问题讨论】:
-
考虑将任何过滤代码或共享列表移动到
BookService。这样,您可以从那里共享完整或过滤的列表。任何使用BookService的组件都可以使用它们。
标签: angular typescript firebase firebase-realtime-database observable