I am new to Angular5 and I am right now using Firebase to fetch data for displaying my page. I googled a few examples of how to get data from firebase using AngularFire but a lot of them are out-dated. And finally I figured out I should use Observables and subscribe it.
service.ts
constructor(private db: AngularFireDatabase) {
}
shows: Show[] = [];
getShows(): Show[] {
const response = (this.db.list('show/data')
.valueChanges() as Observable<Show[]>)
.subscribe(
data => {
data.forEach(element => {
console.log(element);
console.log(typeof element);
this.shows.push(element);
});
}
);
console.log(this.shows);
return this.shows;
}
I console.log both the data I fetched from subscribe() and the data out of the subscribe() function. And the second console.log came out first with an empty [] and the console.log in the subscribe() came out later with each individual object I got from firebase.
Theoretically, as the time I run the second console.log, this.shows is empty and when it returned no data was fetched and the page should not display anything. However, in the app component, when I run the service to get shows, i can still get the information I want and the pages were displayed as expected. Why this happened? How can I make sure when the return functions executed, this.shows is empty or not?
Also, I revised my code like this.
//Service.ts
constructor(private db: AngularFireDatabase) {
}
shows: Observable<Show[]>;
getShows(): Observable<Show[]> {
const response = (this.db.list('show/data')
.valueChanges() as Observable<Show[]>);
return response;
}
// show.component.ts
shows: Show[] = [];
ngOnInit() {
this.getShows();
}
getShows(): void {
this.showService.getShows().subscribe(
data => {
data.forEach(element => {
console.log(element);
console.log(typeof element);
this.shows.push(element);
});
},
err => console.error('Observer got an error: ' + err)
);
}
It gave the error of type observable is not assignable to type 'Show[]'. Property 'includes' is missing in type 'Observable'. How can I fix this?
console.log()executes, your asynchronous request has not yet finished executing. - Robby Cornelissen