Ionic2 / Angular2 - 不等待回归

时间:2017-02-22 07:21:50

标签: angular firebase firebase-realtime-database ionic2

我尝试致电我的提供商以获取Firebase数据库的最后一笔交易,但该分配并不等待该函数的返回。

正如您所看到的,在控制台中,我首先得到' undefined' (来自 home中的 console.log() .ts )以及来自' transaction.ts' 提供商的正确身份验证对象的'已认证'

我基于这个Github回答:https://github.com/angular/angularfire2/issues/708#issuecomment-269012111,但问题是我的任务不会触发,我也不知道为什么。

你们有些人有想法吗? 感谢

home.ts

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { AddTransactionPage } from '../add-transaction/add-transaction';

import { Transaction } from '../../providers/transaction';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  lastTransactions;

  constructor(public navCtrl: NavController, private transaction: Transaction) {

  }

  ionViewWillEnter() {
    this.lastTransactions = this.transaction.getLastTransactions();
    console.log(this.lastTransactions);
  }

  public addTransaction(): void {
    this.navCtrl.push(AddTransactionPage);
  }

}

transaction.ts(提供商)

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class Transaction {

  constructor(public http: Http, private angularFire: AngularFire, private auth: Auth) {
  }

  public getLastTransactions(): any {
    this.auth.getUserData().subscribe(auth => {
      console.log('Got Auth', auth);
      let transactions = this.angularFire.database.list('/users/' + auth.auth.uid + '/transactions').map(transactions => {
        return transactions.map(transaction => {
          transaction.category = this.angularFire.database.object('/categories/' + transaction.category_key); //Getting category from another collection
          return transaction;
        });
      }).subscribe(data => {
        return transactions;
      });
    }, error => {
      console.log('Error', error);
      return null;
    });
  }

}

auth.ts(提供者)

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { AngularFire, AuthMethods, AuthProviders } from 'angularfire2';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class Auth {

  user: any;

  constructor(public http: Http, private angularFire: AngularFire) { }

  public getUserData(): Observable<any> {
    return Observable.create(observer => {
      this.angularFire.auth.subscribe(auth => {
        if(auth)
        {
          this.user = auth;
          observer.next(auth);
        } else {
          observer.error();
        }
      }, error => {
        observer.error();
      });
    });
  }
}

0 个答案:

没有答案