I retrieve my data from Firebase in a function of my service asynchronously and I would like to retrieve them in my component.
I have data in my database, the function returns my data well but I can not retrieve them in my home.ts (array empty).
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);
}
}
I do not know where my problem comes from .. Is it normal that the "=== HOME ===" first appears in the console ?
Thank you in advance for your help and thank you to @AJT_82.
I think it is because you are not returning anything from your
.map
. You could also make it simpler with a filter statement.If you still want to log out the status as it is selected you could use
You also need to wait for the
subscribe
to finish before logging