I'd like to have a service in an Angular2 app that does all the database work. All the tutorials I see use http instead of firebase so they aren't really helpful. I have the service constructor pull the data I'll need from the database, however when a page tries to get data from the service, it doesn't get anything because the database call hasn't finished yet. I'm starting to feel like this post, that there isn't any point in putting network calls in a service, that they should all be duplicate code in each controller instead of putting all the DB code in 1 service. Here are my files:
lesson.service.ts
import { Injectable, OnInit } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
export class Lesson {
constructor(public id: number, public buttons: Object[]) { }
}
@Injectable()
export class LessonService implements OnInit {
private lessons: Lesson[] = [];
constructor(public db: AngularFireDatabase) {
}
ngOnInit() {
this.db.object('/lessons', { preserveSnapshot: true }).subscribe(lessons => {
lessons.forEach(lesson => {
this.lessons.push(new Lesson(
lesson.key,
lesson.val()['buttons']
));
});
});
}
getLessons() {
console.log('getting lessons', this.lessons);
return this.lessons;
}
getLesson(id: number): Lesson {
// return new Promise()
console.log('getLesson', this.lessons);
return this.lessons.filter(lesson => {
return lesson.id === id;
})[0];
}
}
lesson.ts
import { Component, OnInit, Input } from '@angular/core';
import { Lesson, LessonService } from '../lesson.service';
@Component({
selector: 'lesson',
templateUrl: './lesson.html',
styleUrls: ['./lesson.scss']
})
export class LessonComponent implements OnInit {
@Input() lessonID: number = 0;
lesson: Lesson;
constructor(public service: LessonService) { }
ngOnInit() {
this.lesson = this.service.getLesson(this.lessonID);
console.log('view lessons', this.lesson);
}
}
lesson.html
<lesson [lessonID]="selectedId"></lesson>
When I try to load the lesson component, it sees that there is no lessons because this.lessons
isn't filled out from the DB from the service's constructor. The only 'solution' I see is to remove the lesson service, and do DB calls every page load, which in my mind defeats the purpose of doing a single page app.