首页 > 解决方案 > Angular Observable,在组件内共享数据

问题描述

我正在 Angular 上制作我的第一个应用程序。我试图按性别属性过滤书籍对象列表。我在组件之间共享数据时遇到困难:filteredData变量和书籍列表FireBaseList

我正在尝试将filteredData变量从fixed-nav.componentto 传递给books-grid.component. 根据我的研究,我知道我需要让books-grid.component“bookList”可以观察到任何变化,并让bookListonfixed-nav.component.ts发出关于任何变化的事件this.bookList

但是,我无法做到这一点。我知道已经有很多关于 observables 的问题,但没有一个使用 Firebase。希望有大神能帮帮我,谢谢!!

我用作过滤器的固定导航组件

    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() {
      }

    }

书籍-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');
  }
}

书籍.model.ts

    export class Book {
      $key: string;
      title: string;
      author: string;
      gender: string;
      language: string;
      image: string;
      likes: number;
      price: number;
      new: boolean;
    }

标签: angulartypescriptfirebasefirebase-realtime-databaseobservable

解决方案


在您book.service.ts创建一个filterdData变量和函数来设置filterdData如下。Subject使用导入import { Subject } from 'rxjs';

 filteredData  = new Subject<any>();

  setFilteredData(data) {
    this.filteredData.next(data);
  }

然后在您fixed-nav.component.ts完成过滤后的过滤集中过滤数据,如下所示

 this.bookService.setFilteredData(filteredData);

最后从下面订阅filteredDatain并将数据分配给您想要的变量。book.service.tsbooks-grid.component.ts

 constructor(private bookService: BookService) {
     bookService.filteredData.subscribe((data)=>{
      // Assign the data into variable that you want e.g this.filteredData = data;
    })
 }

希望这会帮助你!


推荐阅读