我基本上需要一个共享服务,它将来自Firebase的实时数据存储在一个变量中。然后,各种组件将调用服务中的自定义方法,该方法将从数据存储返回最新数据。这意味着即时数据而不是必须获取数据,这是我从Service返回FirebaseObservableList时的情况。希望你理解
请查看服务
import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable, FirebaseListObservable } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
@Injectable()
export class TransactionService {
protected userTransactions;
private bought: Array<any> = [];
constructor(private db: AngularFireDatabase, private auth: AuthService) {
// Listener to User Transactions
this.getUserTransactions(this.auth.getUserKey())
.subscribe((transactions) => {
this.userTransactions = transactions;
this.processTransactions();
});
}
getUserTransactions(userKey: string): FirebaseListObservable<any[]> {
return this.db.list('/UserTransactions/' + userKey);
}
getCurrentUserTransactions() {
return this.userTransactions;
}
/**
* Process the Transactions and
* Categorize them
*/
processTransactions() {
this.rewarded = [];
this.userTransactions.forEach(transaction => {
let rewardType = transaction.transactiontype;
switch (rewardType) {
case "bought":
this.bought.push(transaction);
break;
default:
break;
}
});
}
getBought() {
return this.bought;
}
}
现在是组件
import { Component, OnInit } from '@angular/core';
import { trigger, state, transition, style, animate } from '@angular/animations';
// Services
import { TransactionService } from '../../../services/transaction.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
animations: [
trigger('fadeInOut', [
transition('void => *', [
style({ opacity: 0 }),
animate(150, style({ opacity: 1 }))
]),
transition('* => void', [
animate(150, style({ opacity: 0 }))
])
])
],
})
export class HomeComponent implements OnInit {
public bought: Array<any>;
public activeTab: string = 'recieved';
constructor(private transactions: TransactionService) {
this.bought = this.transactions.getBought();
}
ngOnInit() {
}
}
PS:我对Angular2和Observables
很新答案 0 :(得分:0)
所以Guys终于找到了答案。创建了另一个Observable(BehaviorSubject)来存储最新数据。然后组件订阅了这个可观察对象。
private _rewards: BehaviorSubject<any[]>;
constructor(private db: AngularFireDatabase, private auth: AuthService) {
this.dataStore = {
rewards: [],
};
this._rewards = <BehaviorSubject<any[]>>new BehaviorSubject([]);
this.subscribeToRewarded();
}
subscribeToRewarded() {
this.db.list('< DB Path >', {
query: {
orderByChild: 'transactiontype',
equalTo: "reward"
}
}).subscribe((reward) => {
this._rewards.next(reward);
});
}
getRewarded() {
return this._rewards.asObservable();
}