Angular Observable,在组件内共享数据 [英] Angular Observable, sharing data within components

查看:73
本文介绍了Angular Observable,在组件内共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making my first App on Angular. I trying to filter a list of book objects by the gender attribute. I am having difficulty sharing data between components: the filteredData variable and the list of books FireBaseList.

我正在尝试将filteredData变量从fixed-nav.component传递给books-grid.component.从我的研究中,我知道我需要使books-grid.component"bookList"可以观察到任何更改,并使fixed-nav.component.ts上的bookList发出关于this.bookList

I am trying to pass the filteredData variable from fixed-nav.component to books-grid.component. From my research, I know I need to make the books-grid.component "bookList" observable of any changes and have the bookList on fixed-nav.component.ts emit an event on any changes on this.bookList

但是,我无法实现这一目标.我知道已经有很多关于可观测对象的问题,但是没有一个使用Firebase.希望有任何人能帮助我,谢谢!!

However, I am unable to achieve this. I know there are many questions about observables already but none use Firebase. Hope anyone out there can help me, THANKS!!

fixed-nav.component

fixed-nav.component that I use as filter

    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

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

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

books.model.ts

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

推荐答案

在您的book.service.ts中,创建一个filterdData变量并设置filterdData的函数,如下所示.使用import { Subject } from 'rxjs';

In your book.service.ts create a filterdData variable and function to set filterdData like below. Import Subject using import { Subject } from 'rxjs';

 filteredData  = new Subject<any>();

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

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

And then in your fixed-nav.component.ts after done filtration set that filtered data like below

 this.bookService.setFilteredData(filteredData);

最后像下面一样从books-grid.component.ts预订book.service.tsbook.service.ts中的filteredData,然后将数据分配到所需的变量中.

Finally subscribe to the filteredData in book.service.ts from books-grid.component.ts like below and assign the data into variable that you want.

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

希望这对您有帮助!

这篇关于Angular Observable,在组件内共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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