从组件中的异步服务检索数据

时间:2017-07-26 09:22:34

标签: angular typescript asynchronous ionic-framework

我在异步的服务函数中从Firebase检索我的数据,我想在我的组件中检索它们。

我的数据库中有数据,该函数可以很好地返回我的数据,但我无法在home.ts(数组为空)中检索它们。

Screen of console.log

todolistService.ts:

    import {Injectable} from '@angular/core';
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import * as moment from 'moment';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs/Observable";

@Injectable()
export class TodolistService {

  statuts: Array<any> = [];
  dateOfTheDay: string;

  constructor(public afDB: AngularFireDatabase) {
    moment.locale('fr');
    this.dateOfTheDay = moment().format('L'); // Date au format : 04/07/2017
  }

  /**
   *
   * @returns {Observable<Array<any>>}
   */
  statusToShow():Observable<Array<any>> {
    let localStatuts: Array<any> = [];
    return this.afDB.list('/statut').map(status => {
      for (let s of status) {
        if (this.dateOfTheDay === s.statut_date_tache) {
          if (s.statut_id_tache in this.statuts === false) {
            localStatuts[s.statut_id_tache] = s;
            console.log('=== STATUSTOSHOW ===');
            console.log(localStatuts);
            return localStatuts;
          }
        }
      }
    });
  }
}

home.ts:

    import {Component} from '@angular/core';
import {ModalController, NavController} from 'ionic-angular';
import {TodolistService} from "../../providers/todolistService";

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

  public statusOfTheDay: Array<any> = [];

  constructor(public navCtrl: NavController, public modalCtrl: ModalController, public todolistService: TodolistService) {

  }

  ionViewDidLoad() {
    this.todolistService.statusToShow().subscribe(status => this.statusOfTheDay = status);
    console.log('=== HOME ===');
    console.log(this.statusOfTheDay);
  }
}

我不知道我的问题来自哪里。“=== HOME ===”首次出现在控制台中是否正常?

提前感谢您的帮助,并感谢@ AJT_82。

1 个答案:

答案 0 :(得分:0)

我认为这是因为你没有从.map返回任何内容。您还可以使用过滤器语句使其更简单。

return this.afDB.list('/statut').map(status => {
  return status.filter(s => this.dateOfTheDay === s.statut_date_tache && (s.statut_id_tache in this.statuts === false));
});

如果您仍想注销状态,可以使用

return this.afDB.list('/statut').map(status => {
  return status.filter(s => {
    if (this.dateOfTheDay === s.statut_date_tache && (s.statut_id_tache in this.statuts === false))) {
      console.log (s);
      return true;
    }
    return false;
  }
});

您还需要在记录

之前等待subscribe完成
ionViewDidLoad() {
  this.todolistService.statusToShow().subscribe(status => {
    this.statusOfTheDay = status;
    console.log('=== HOME ===');
    console.log(this.statusOfTheDay);
  });
}